From 760af9c4ddf471447f0023e7ef35c34502828dc4 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 19:51:40 +0100 Subject: [PATCH 01/37] Give each restart asset of a portfolio its own cutoff A homogeneous portfolio of restart-based engines, PBS, gave every asset a PbsCutoff that drew its values from one cutoff shared under a mutex. The assets thus advanced a single sequence together, and a random cutoff made all assets restart from the same sequence of values. Cutoff now has a pure virtual copy() that returns a generator in the same state, and each asset that takes ownership of the cutoff gets its own copy. A copy of a random cutoff draws its own sequence. The portfolio deletes the original once it has been built; if building throws, the caller keeps the cutoff, as with RBS. Nested portfolios of restart-based engines are handled the same way, and other engines do not take the cutoff and are left unchanged. This replaces PbsCutoffs, PbsCutoff, make_pbs_cutoffs(), and release_pbs_cutoffs(). --- changelog.in | 11 +++ docs/gecode-7-migration.md | 28 ++++++++ gecode/search.hh | 48 ++++++++++++- gecode/search/cutoff.cpp | 62 +++++++++++++++++ gecode/search/cutoff.hpp | 3 +- gecode/search/pbs.hpp | 135 ++++++++----------------------------- test/search.cpp | 69 ++++++++++++++++++- 7 files changed, 243 insertions(+), 113 deletions(-) diff --git a/changelog.in b/changelog.in index 5da2d434d0..4a47382c55 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,17 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: change +Rank: major +[DESCRIPTION] +Give each restart-based asset of a portfolio its own copy of the cutoff. +[MORE] +Cutoff has a new pure virtual function copy(), which custom cutoff generators +must implement. Copies of a random cutoff draw different sequences, so the +assets restart at different times. See docs/gecode-7-migration.md. + [ENTRY] Module: search What: change diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 0e20ce7921..60505775e9 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -39,3 +39,31 @@ The examples show typical overrides: large neighbourhood search. - `examples/qcp.cpp`: a PBS `spoke()` that posts a different branching for each asset. + +## Cutoff generators implement copy() + +`Search::Cutoff` has a new pure virtual member function: + +```cpp +virtual Gecode::Search::Cutoff* copy(void) const; +``` + +It returns a copy of the generator in its current state that continues the +sequence on its own. A copy of `Cutoff::rnd()` draws its own random +sequence, so that the assets restart at different times. A portfolio of +restart-based engines, `PBS`, gives each asset its own copy of the +cutoff in its options and deletes the original once the portfolio is built. +In Gecode 6.6, the assets drew their values from one shared cutoff sequence. + +A custom cutoff generator must implement `copy()`. For a generator whose +state is plain data, the copy constructor suffices: + +```cpp +Gecode::Search::Cutoff* +MyCutoff::copy(void) const { + return new MyCutoff(*this); +} +``` + +A generator that owns other generators copies them with their own +`copy()`. diff --git a/gecode/search.hh b/gecode/search.hh index 05d2a8057c..070b170ad3 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -487,6 +487,15 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const = 0; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void) = 0; + /** + * \brief Return a copy of this generator in its current state + * + * The copy continues the sequence independently of this generator, + * except that a copy of a random generator draws its own sequence + * (see CutoffRandom::copy()). A portfolio of restart-based engines + * gives each asset its own copy. + */ + virtual Cutoff* copy(void) const = 0; /// Destructor virtual ~Cutoff(void); //@} @@ -542,6 +551,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; }; /** @@ -561,6 +572,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; }; /** @@ -588,6 +601,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; }; /** @@ -609,6 +624,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; }; /** @@ -627,6 +644,8 @@ namespace Gecode { namespace Search { unsigned long long int step; /// Current value unsigned long long int cur; + /// Number of copies made of this generator + mutable unsigned int copies; public: /// Constructor CutoffRandom(unsigned int seed, @@ -636,6 +655,17 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /** + * \brief Return a copy of this generator with its own random sequence + * + * The copy draws its values, starting with its current one, from a + * seed that depends on the state of this generator and on how many + * copies of it have been made before. Copies made one after the + * other thus have different sequences, so that the assets of a + * portfolio restart at different times, and the same program + * creates the same sequences. + */ + virtual Cutoff* copy(void) const; }; /** @@ -657,6 +687,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; /// Destructor virtual ~CutoffAppend(void); }; @@ -678,6 +710,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; /// Destructor virtual ~CutoffMerge(void); }; @@ -703,6 +737,8 @@ namespace Gecode { namespace Search { virtual unsigned long long int operator ()(void) const; /// Increment and return the next cutoff value virtual unsigned long long int operator ++(void); + /// Return a copy of this generator in its current state + virtual Cutoff* copy(void) const; /// Destructor virtual ~CutoffRepeat(void); }; @@ -1470,7 +1506,12 @@ namespace Gecode { class RBS : public Search::Base { using Search::Base::e; public: - /// Initialize engine for space \a s and options \a o + /** + * \brief Initialize engine for space \a s and options \a o + * + * The engine takes ownership of the cutoff in \a o. If the + * constructor throws an exception, the caller keeps the cutoff. + */ RBS(T* s, const Search::Options& o); /// Whether engine does best solution search static const bool best = E::best; @@ -1546,8 +1587,9 @@ namespace Gecode { * PBS does not allocate workers or adjust those controls. * * When the assets are restart-based engines, the portfolio takes - * ownership of the cutoff in \a o and the assets share its sequence: - * each restart of an asset takes the next value of the sequence. + * ownership of the cutoff in \a o and gives each asset its own copy + * (see Cutoff::copy()). If the constructor throws an exception, the + * caller keeps the cutoff. * * The class \a T can implement member functions * \code virtual bool hub(const MetaInfo& mi) \endcode diff --git a/gecode/search/cutoff.cpp b/gecode/search/cutoff.cpp index 54a5483d4b..be173d5943 100755 --- a/gecode/search/cutoff.cpp +++ b/gecode/search/cutoff.cpp @@ -36,6 +36,7 @@ */ #include +#include #include namespace Gecode { namespace Search { @@ -49,6 +50,11 @@ namespace Gecode { namespace Search { return c; } + Cutoff* + CutoffConstant::copy(void) const { + return new CutoffConstant(*this); + } + unsigned long long int CutoffLinear::operator ()(void) const { @@ -60,6 +66,11 @@ namespace Gecode { namespace Search { return n; } + Cutoff* + CutoffLinear::copy(void) const { + return new CutoffLinear(*this); + } + unsigned long int CutoffLuby::start[CutoffLuby::n_start] = { @@ -75,6 +86,11 @@ namespace Gecode { namespace Search { return scale*luby(i++); } + Cutoff* + CutoffLuby::copy(void) const { + return new CutoffLuby(*this); + } + unsigned long long int CutoffGeometric::operator ()(void) const { @@ -86,6 +102,11 @@ namespace Gecode { namespace Search { return static_cast(scale * n); } + Cutoff* + CutoffGeometric::copy(void) const { + return new CutoffGeometric(*this); + } + unsigned long long int CutoffRandom::operator ++(void) { @@ -97,6 +118,17 @@ namespace Gecode { namespace Search { return cur; } + Cutoff* + CutoffRandom::copy(void) const { + CutoffRandom* c = new CutoffRandom(*this); + // Derive a distinct seed for each copy, the golden ratio spreads them + copies++; + c->rnd.seed(rnd.seed() + copies * 0x9e3779b9U); + c->copies = 0U; + (void) ++(*c); + return c; + } + unsigned long long int CutoffAppend::operator ()(void) const { @@ -116,6 +148,16 @@ namespace Gecode { namespace Search { } } + Cutoff* + CutoffAppend::copy(void) const { + std::unique_ptr d1(c1->copy()); + std::unique_ptr d2(c2->copy()); + Cutoff* d = new CutoffAppend(d1.get(),n,d2.get()); + (void) d1.release(); + (void) d2.release(); + return d; + } + unsigned long long int CutoffMerge::operator ()(void) const { @@ -128,6 +170,16 @@ namespace Gecode { namespace Search { return (*c1)(); } + Cutoff* + CutoffMerge::copy(void) const { + std::unique_ptr d1(c1->copy()); + std::unique_ptr d2(c2->copy()); + Cutoff* d = new CutoffMerge(d1.get(),d2.get()); + (void) d1.release(); + (void) d2.release(); + return d; + } + unsigned long long int CutoffRepeat::operator ()(void) const { @@ -143,6 +195,16 @@ namespace Gecode { namespace Search { return cutoff; } + Cutoff* + CutoffRepeat::copy(void) const { + std::unique_ptr d1(c->copy()); + CutoffRepeat* d = new CutoffRepeat(d1.get(),n); + (void) d1.release(); + d->cutoff = cutoff; + d->i = i; + return d; + } + Cutoff* Cutoff::constant(unsigned long long int scale) { diff --git a/gecode/search/cutoff.hpp b/gecode/search/cutoff.hpp index 441a286e1f..c52b82d6b5 100755 --- a/gecode/search/cutoff.hpp +++ b/gecode/search/cutoff.hpp @@ -91,7 +91,8 @@ namespace Gecode { namespace Search { unsigned long long int n0) : rnd(seed), min(min0), n(n0), step(std::max(1ULL, - static_cast((max0-min0+1U)/n))) { + static_cast((max0-min0+1U)/n))), + copies(0U) { cur = ++(*this); } diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index b5d2a67c9e..96c6ee48b5 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -129,109 +129,34 @@ namespace Gecode { namespace Search { }; /** - * \brief Cutoff sequence shared by the assets of a portfolio + * \brief Return the cutoff for the next asset of a portfolio * - * A cutoff cannot be copied, so the assets of a portfolio that each take - * ownership of a cutoff get a PbsCutoff each, drawing from one sequence. - * The sequence is disposed with the last PbsCutoff and the reference held - * while the portfolio is built. The original cutoff is disposed as well - * only if building has succeeded, otherwise it stays with the caller. - * - * \internal - */ - class PbsCutoffs : public HeapAllocated { - public: - /// Mutex protecting the sequence, assets can run in parallel - Support::Mutex m; - /// The shared cutoff sequence - Cutoff* c; - /// Number of references - unsigned int n; - /// Whether the cutoff sequence is disposed with the last reference - bool owner; - /// Initialize for cutoff \a c0 with the reference held while building - PbsCutoffs(Cutoff* c0) : c(c0), n(1U), owner(false) {} - /// Release a reference - static void release(PbsCutoffs* s) { - bool last; - { - Support::Lock lock(s->m); - last = (--s->n == 0U); - } - if (last) { - if (s->owner) - delete s->c; - delete s; - } - } - }; - - /** - * \brief Cutoff of a portfolio asset, the assets share the sequence of values - * \internal - */ - class PbsCutoff : public Cutoff { - protected: - /// The shared sequence - PbsCutoffs* s; - /// The current cutoff value of this asset - unsigned long long int v; - public: - /// Initialize as a new reference to \a s0 - PbsCutoff(PbsCutoffs* s0) : s(s0) { - Support::Lock lock(s->m); - v = (*s->c)(); - s->n++; - } - /// Return the current cutoff value - unsigned long long int operator ()(void) const override { - return v; - } - /// Take the next value of the shared sequence and return it - unsigned long long int operator ++(void) override { - Support::Lock lock(s->m); - v = ++(*s->c); - return v; - } - /// Release the reference to the shared sequence - ~PbsCutoff(void) override { - PbsCutoffs::release(s); - } - }; - - /** - * \brief Return the cutoffs shared by the assets of a portfolio - * - * Returns nullptr if the assets of engine \a E do not take ownership of - * the cutoff in \a opt, or if there are fewer than two assets. + * When the assets of engine \a E take ownership of the cutoff \a c, + * each asset gets its own copy of \a c, and the portfolio deletes \a c + * once it has been built. Otherwise the assets share \a c and the caller + * keeps it. * * \internal */ template - forceinline PbsCutoffs* - make_pbs_cutoffs(const Options& opt, unsigned int n_assets) { - if (!PbsOwnsCutoff::value || (opt.cutoff == nullptr) || - (n_assets < 2U)) + forceinline std::unique_ptr + pbs_cutoff(const Cutoff* c) { + if (!PbsOwnsCutoff::value || (c == nullptr)) return nullptr; - return new PbsCutoffs(opt.cutoff); + return std::unique_ptr(c->copy()); } /** - * \brief Release the cutoffs \a cs held while building - * - * The flag \a built tells whether building has succeeded. + * \brief Delete the cutoff \a c of a built portfolio if its assets of + * engine \a E own copies * * \internal */ + template forceinline void - release_pbs_cutoffs(PbsCutoffs* cs, bool built) { - if (cs == nullptr) - return; - { - Support::Lock lock(cs->m); - cs->owner = built; - } - PbsCutoffs::release(cs); + pbs_release_cutoff(Cutoff* c) { + if (PbsOwnsCutoff::value) + delete c; } /// A PBS engine builder @@ -319,8 +244,8 @@ namespace Gecode { namespace Search { WrapTraceRecorder::engine(opt.tracer, SearchTracer::EngineType::PBS, n_assets); + Cutoff* cutoff = opt.cutoff; Space* unowned_hub = hub; - PbsCutoffs* cutoffs = make_pbs_cutoffs >(opt,n_assets); try { for (unsigned int i=0U; ispoke(i); - std::unique_ptr cutoff; - if (cutoffs != nullptr) { - cutoff.reset(new PbsCutoff(cutoffs)); - opt.cutoff = cutoff.get(); - } + std::unique_ptr c(pbs_cutoff >(cutoff)); + if (c != nullptr) + opt.cutoff = c.get(); assets[i] = build(spoke.get(),opt); // The asset owns its cutoff - (void) cutoff.release(); + (void) c.release(); } Engine* e = Seq::pbsengine( assets,stops,n_assets,stat,opt,E::best); - release_pbs_cutoffs(cutoffs,true); + pbs_release_cutoff >(cutoff); return e; } catch (...) { pbscleanup(assets,stops,n_assets,unowned_hub); - release_pbs_cutoffs(cutoffs,false); throw; } } @@ -421,8 +343,8 @@ namespace Gecode { namespace Search { stops[i] = nullptr; } + Cutoff* cutoff = opt.cutoff; Space* unowned_hub = hub; - PbsCutoffs* cutoffs = make_pbs_cutoffs >(opt,n_assets); try { for (unsigned int i=0U; ispoke(static_cast(i)); - std::unique_ptr cutoff; - if (cutoffs != nullptr) { - cutoff.reset(new PbsCutoff(cutoffs)); - opt.cutoff = cutoff.get(); - } + std::unique_ptr c(pbs_cutoff >(cutoff)); + if (c != nullptr) + opt.cutoff = c.get(); assets[i] = build(spoke.get(),opt); // The asset owns its cutoff - (void) cutoff.release(); + (void) c.release(); } Engine* e = Par::pbsengine(assets,stops,n_assets,stat,E::best); - release_pbs_cutoffs(cutoffs,true); + pbs_release_cutoff >(cutoff); return e; } catch (...) { pbscleanup(assets,stops,n_assets,unowned_hub); - release_pbs_cutoffs(cutoffs,false); throw; } } diff --git a/test/search.cpp b/test/search.cpp index 2a3000b1b8..328c6c5b7b 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -3333,7 +3333,74 @@ namespace Test { PBSBuilderStop pbs_builder_stop; - /// Restart-based assets of a portfolio share the cutoff sequence + /// A copy of a cutoff generator continues its sequence independently + class CutoffCopy : public Base { + /// Check that a copy of \a c continues as \a c, then delete \a c + static bool same(Gecode::Search::Cutoff* c) { + std::unique_ptr o(c); + for (int i=0; i<5; i++) + (void) ++(*o); + std::unique_ptr d(o->copy()); + if ((*d)() != (*o)()) + return false; + for (int i=0; i<20; i++) + if (++(*d) != ++(*o)) + return false; + return true; + } + public: + CutoffCopy(void) : Base("Search::Cutoff::Copy") {} + bool run(void) override { + using Gecode::Search::Cutoff; + return same(Cutoff::constant(3)) && same(Cutoff::linear(2)) && + same(Cutoff::geometric(2,1.5)) && same(Cutoff::luby(2)) && + same(Cutoff::append(Cutoff::linear(1),8,Cutoff::luby(3))) && + same(Cutoff::merge(Cutoff::linear(1),Cutoff::geometric(1,2.0))) && + same(Cutoff::repeat(Cutoff::linear(4),3)); + } + }; + + CutoffCopy cutoff_copy; + + /// Copies of a random cutoff generator draw distinct, reproducible sequences + class CutoffRandomCopy : public Base { + /// Return the first values of \a c, which is deleted + static std::vector + values(Gecode::Search::Cutoff* c) { + std::unique_ptr d(c); + std::vector v{(*d)()}; + for (int i=0; i<20; i++) { + v.push_back(++(*d)); + if ((v.back() < 1U) || (v.back() > 1000U)) + return {}; + } + return v; + } + /// Return the values of two copies of a generator with seed \a seed + static std::vector > + copies(unsigned int seed) { + std::unique_ptr + o(Gecode::Search::Cutoff::rnd(seed,1,1000,1000)); + (void) ++(*o); + std::vector > v; + v.push_back(values(o->copy())); + v.push_back(values(o->copy())); + v.push_back(values(o.release())); + return v; + } + public: + CutoffRandomCopy(void) : Base("Search::Cutoff::RandomCopy") {} + bool run(void) override { + std::vector > v = copies(7); + return !v[0].empty() && !v[1].empty() && !v[2].empty() && + (v[0] != v[1]) && (v[0] != v[2]) && (v[1] != v[2]) && + (copies(7) == v); + } + }; + + CutoffRandomCopy cutoff_random_copy; + + /// Each restart-based asset of a portfolio owns a copy of the cutoff class PBSRestartCutoff : public Base { template class Engine> static bool test(unsigned int threads) { From 513443145b8b024f02ba6c60f948e56a35f21b01 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 20:02:51 +0100 Subject: [PATCH 02/37] Replace stopped() with end_reason() stopped() could not tell an exhausted search from a search that ended without exhausting its search space, so callers took a search that was not stopped as a proof. Search engines now report why next() returned no solution with end_reason(): Exhausted, Incomplete, or Limit, and NotEnded while next() returns solutions. stopped() and the experimental limited() are removed without a replacement alias. Restart-based search reports Exhausted when its hub fails, Limit only for its own stop object, and the end reason of a complete spoke search otherwise. CABS and the parallel frontier engine report Incomplete at their width or frontier limit. Portfolio search keeps its previous behaviour in terms of the new end reasons. FlatZinc reports optimality and unsatisfiability only for an exhausted search, and the script driver reports an incomplete search. --- changelog.in | 13 ++++++ docs/gecode-7-migration.md | 31 ++++++++++++++ examples/job-shop.cpp | 9 ++-- gecode/driver/script.hpp | 6 ++- gecode/flatzinc/flatzinc.cpp | 7 ++-- gecode/search.hh | 49 +++++++++++++++++----- gecode/search/base.hpp | 6 +-- gecode/search/cabs.cpp | 19 ++------- gecode/search/engine.cpp | 7 ---- gecode/search/par/engine.hh | 6 ++- gecode/search/par/engine.hpp | 15 ++++--- gecode/search/par/frontier.cpp | 24 ++++++----- gecode/search/par/frontier.hh | 8 ++-- gecode/search/par/pbs.hh | 14 +++---- gecode/search/par/pbs.hpp | 37 +++++++---------- gecode/search/seq/cabs.hh | 4 +- gecode/search/seq/dead.cpp | 17 +++++--- gecode/search/seq/lds.hh | 8 ++-- gecode/search/seq/lds.hpp | 21 +++++++--- gecode/search/seq/pbs.hh | 16 ++++---- gecode/search/seq/pbs.hpp | 35 +++++++--------- gecode/search/seq/rbs.cpp | 41 +++++++++++-------- gecode/search/seq/rbs.hh | 8 ++-- gecode/search/seq/rbs.hpp | 2 +- gecode/search/support.hh | 20 +++++---- gecode/search/worker.hh | 7 ++++ test/int/open-var-list.cpp | 2 +- test/nogoods.cpp | 2 +- test/search.cpp | 75 +++++++++++++++++++--------------- 29 files changed, 301 insertions(+), 208 deletions(-) diff --git a/changelog.in b/changelog.in index 4a47382c55..158af60945 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,19 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: change +Rank: major +[DESCRIPTION] +Replace stopped() of search engines by end_reason(). +[MORE] +end_reason() tells why next() returned no solution: EndReason::Exhausted is a +proof, EndReason::Incomplete is an end without one, and EndReason::Limit is a +stop. stopped() and the experimental limited() are removed. FlatZinc reports +optimality or unsatisfiability only for an exhausted search. See +docs/gecode-7-migration.md. + [ENTRY] Module: search What: change diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 60505775e9..3886e665af 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -67,3 +67,34 @@ MyCutoff::copy(void) const { A generator that owns other generators copies them with their own `copy()`. + +## stopped() is replaced by end_reason() + +`Search::Engine::stopped()` and `Search::Base::stopped()` are removed, +and so is the experimental `limited()`. After `next()` returns no solution, +`end_reason()` tells why: + +```cpp +enum class Gecode::Search::EndReason : unsigned char { + NotEnded, Exhausted, Incomplete, Limit +}; +``` + +| Gecode 6 | Gecode 7 | +|-----------------------------------------------|-------------------------------------------------| +| `stopped()` is true | `end_reason() == EndReason::Limit` | +| `stopped()` is false after no solution | `end_reason() == EndReason::Exhausted` or `EndReason::Incomplete` | +| `limited()` is true (AStar, CABS) | `end_reason() == EndReason::Incomplete` | +| last `next()` returned a solution | `end_reason() == EndReason::NotEnded` | + +`Exhausted` means that the engine explored everything it was asked to +explore: there is no further solution, and the last solution of a +branch-and-bound search is optimal. `Incomplete` means that the engine ended +on its own without that proof, for example CABS at its width limit. Calling +`next()` again does not continue an incomplete search. `Limit` means that a +stop object stopped the engine, and calling `next()` again continues the +search. + +Code that used `!stopped()` as a proof, such as reporting optimality, should +test for `EndReason::Exhausted`. Code that resumes a search after a limit +should test for `EndReason::Limit`. diff --git a/examples/job-shop.cpp b/examples/job-shop.cpp index d497ded4c3..33f5eef2db 100755 --- a/examples/job-shop.cpp +++ b/examples/job-shop.cpp @@ -790,11 +790,12 @@ solve(const JobShopOptions& opt) { s->print(std::cout); u = s->cost().val(); delete s; - } else if (rbs.stopped()) { + } else if (rbs.end_reason() == Search::EndReason::Exhausted) { + l = m+1; + } else { + // Stopped, or ended without proving that no solution exists stopped = true; break; - } else { - l = m+1; } } @@ -842,7 +843,7 @@ solve(const JobShopOptions& opt) { Driver::stop(t,std::cout); std::cout << std::endl; - if (rbs.stopped()) { + if (rbs.end_reason() != Search::EndReason::Exhausted) { std::cout << "\t\t\t\tstopped due to time-out..." << std::endl; std::cout << std::endl << "\tSolution at most "; diff --git a/gecode/driver/script.hpp b/gecode/driver/script.hpp index 1c8f707088..8a83556fd2 100755 --- a/gecode/driver/script.hpp +++ b/gecode/driver/script.hpp @@ -427,7 +427,9 @@ namespace Gecode { namespace Driver { CombinedStop::installCtrlHandler(false); Search::Statistics stat = e.statistics(); s_out << endl; - if (e.stopped()) { + if (e.end_reason() == Search::EndReason::Incomplete) { + l_out << "Search engine finished without exhausting the search space" << '\n' << '\n'; + } else if (e.end_reason() == Search::EndReason::Limit) { l_out << "Search engine stopped..." << endl << "\treason: "; int r = static_cast(so.stop)->reason(stat,so); @@ -572,7 +574,7 @@ namespace Gecode { namespace Driver { delete ex; s_n++; } while (s_n < s_l); - if (e.stopped()) + if (e.end_reason() == Search::EndReason::Limit) stopped = true; } delete sok.stop; diff --git a/gecode/flatzinc/flatzinc.cpp b/gecode/flatzinc/flatzinc.cpp index 52b9b0fdc2..c9731cc107 100644 --- a/gecode/flatzinc/flatzinc.cpp +++ b/gecode/flatzinc/flatzinc.cpp @@ -1941,7 +1941,8 @@ namespace Gecode { namespace FlatZinc { bool printAll = _method == SAT || opt.allSolutions() || noOfSolutions != 0; int findSol = noOfSolutions; bool solution_limit_reached = false; - bool engine_stopped = false; + // Only an exhausted search proves optimality or unsatisfiability + bool proof = false; Gecode::Search::Statistics stat; std::unique_ptr sol; { @@ -1962,7 +1963,7 @@ namespace Gecode { namespace FlatZinc { break; } } - engine_stopped = se.stopped(); + proof = se.end_reason() == Search::EndReason::Exhausted; if (opt.mode() == SM_STAT) { stat = se.statistics(); } @@ -1976,7 +1977,7 @@ namespace Gecode { namespace FlatZinc { out << "----------" << std::endl; } if (!solution_limit_reached) { - if (!engine_stopped) { + if (proof) { if (sol) { out << "==========" << std::endl; } else { diff --git a/gecode/search.hh b/gecode/search.hh index 070b170ad3..0e51e75a38 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1093,6 +1093,36 @@ namespace Gecode { namespace Search { namespace Gecode { namespace Search { + /** + * \brief Why the last call to next() of a search engine returned no solution + * + * A search engine reports the reason with end_reason(). Only + * Exhausted is a proof: the space that the engine was given has no + * further solutions (no better ones for best solution search). Any + * other reason after next() returned nullptr means that the engine + * ended without such a proof. + * + * A meta engine (restart-based or portfolio search) reports Limit + * only for a stop object installed above it, not for its own + * cutoffs, slices, or the stop objects of its assets. + * + * \ingroup TaskModelSearch + */ + enum class EndReason : unsigned char { + /// next() has not been called, or the last call returned a solution + NotEnded, + /// The search space is exhausted, calling next() again finds nothing + Exhausted, + /** + * Search finished without exhausting its search space, for example + * at the width limit of CABS. There may be further solutions, but + * calling next() again finds none. + */ + Incomplete, + /// A stop object stopped search, calling next() again resumes it + Limit, + }; + /** * \brief %Search engine implementation interface */ @@ -1109,12 +1139,8 @@ namespace Gecode { namespace Search { virtual Space* next(void) = 0; /// Return statistics virtual Statistics statistics(void) const = 0; - /// Check whether engine has been stopped - virtual bool stopped(void) const = 0; -#ifdef GECODE_HAS_EXPERIMENTAL - /// Whether the engine stopped at a local limit (such as a CABS width limit) and cannot continue - virtual bool limited(void) const; -#endif + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const = 0; /// Constrain future solutions to be better than \a b (raises exception) virtual void constrain(const Space& b); /// Reset engine to restart at space \a s (does nothing) @@ -1148,8 +1174,8 @@ namespace Gecode { namespace Search { virtual T* next(void); /// Return statistics virtual Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Destructor virtual ~Base(void); private: @@ -1446,9 +1472,10 @@ namespace Gecode { * Search::Options::d_l discrepancies, allowing more discrepancies in each * iteration, starting from none. * - * When next() returns nullptr and stopped() returns false, either the - * search tree has been explored completely, or the discrepancy limit has - * been reached while parts of the tree are still unexplored. The engine + * When next() returns nullptr and end_reason() returns + * Search::EndReason::Exhausted, either the search tree has been explored + * completely, or the discrepancy limit has been reached while parts of + * the tree are still unexplored. The engine * does not report which: a search that finds no (further) solution only * proves that none exists if no path of the tree has more discrepancies * than the limit. diff --git a/gecode/search/base.hpp b/gecode/search/base.hpp index a00bcb5174..bdb78a1386 100644 --- a/gecode/search/base.hpp +++ b/gecode/search/base.hpp @@ -52,9 +52,9 @@ namespace Gecode { namespace Search { return e->statistics(); } template - forceinline bool - Base::stopped(void) const { - return e->stopped(); + forceinline EndReason + Base::end_reason(void) const { + return e->end_reason(); } template forceinline diff --git a/gecode/search/cabs.cpp b/gecode/search/cabs.cpp index f012bdb694..e9ab0c9b8f 100644 --- a/gecode/search/cabs.cpp +++ b/gecode/search/cabs.cpp @@ -123,17 +123,6 @@ namespace Gecode { namespace Search { namespace Par { namespace Gecode { namespace Search { namespace Seq { - /// Sequential CABS engine - class CABSEngine : public WorkerToEngine { - public: - /// Initialize for space \a s with options \a o - CABSEngine(Space* s, const Options& o) : WorkerToEngine(s,o) {} - /// Whether search stopped at the width or frontier limit - bool limited(void) const override { - return w.limited(); - } - }; - }}} namespace Gecode { namespace Search { @@ -149,7 +138,7 @@ namespace Gecode { namespace Search { if (e.threads > 1.0) return new Par::CABS(s,e); #endif - return new Seq::CABSEngine(s,e); + return new WorkerToEngine< Seq::CABS>(s,e); } }} @@ -309,9 +298,9 @@ namespace Gecode { namespace Search { namespace Seq { return *this; } - bool - CABS::limited(void) const { - return _limited; + EndReason + CABS::end_reason(void) const { + return _limited ? EndReason::Incomplete : Worker::end_reason(); } void diff --git a/gecode/search/engine.cpp b/gecode/search/engine.cpp index b2a3d31851..63a71d98ff 100644 --- a/gecode/search/engine.cpp +++ b/gecode/search/engine.cpp @@ -49,13 +49,6 @@ namespace Gecode { namespace Search { (void) b; throw NoBest("Engine::constrain"); } -#ifdef GECODE_HAS_EXPERIMENTAL - bool - Engine::limited(void) const { - return false; - } - -#endif void Engine::reset(Space* s) { (void) s; diff --git a/gecode/search/par/engine.hh b/gecode/search/par/engine.hh index 3cd196e36e..50a1be64a1 100644 --- a/gecode/search/par/engine.hh +++ b/gecode/search/par/engine.hh @@ -242,6 +242,8 @@ namespace Gecode { namespace Search { namespace Par { volatile unsigned int n_busy; /// Whether a worker had been stopped std::atomic has_stopped; + /// Why the last call to next() returned no solution + EndReason end; /// Number of calls to next() that have started search std::atomic n_runs; /// Whether search state changed such that signal is needed @@ -265,8 +267,8 @@ namespace Gecode { namespace Search { namespace Par { Engine(const Options& o); /// Return next solution (nullptr, if none exists or search has been stopped) virtual Space* next(void); - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; //@} /// Destructor diff --git a/gecode/search/par/engine.hpp b/gecode/search/par/engine.hpp index 35ed2bf141..00233bc2b6 100644 --- a/gecode/search/par/engine.hpp +++ b/gecode/search/par/engine.hpp @@ -57,9 +57,9 @@ namespace Gecode { namespace Search { namespace Par { return static_cast(opt().threads); } template - forceinline bool - Engine::stopped(void) const { - return has_stopped.load(std::memory_order_acquire); + forceinline EndReason + Engine::end_reason(void) const { + return end; } @@ -125,8 +125,8 @@ namespace Gecode { namespace Search { namespace Par { _opt(o), scheduler_enabled(false), scheduler_fast_admit(nullptr), scheduler_worker(nullptr), scheduler_requested(workers()), - scheduler_leases(0U), scheduler_cursor(0U), scheduler_generation(0U), - _cmd(C_WAIT), solutions(heap) { + scheduler_leases(0U), scheduler_cursor(0U), scheduler_generation(0U), _cmd(C_WAIT), solutions(heap), + end(EndReason::NotEnded) { // Initialize termination information _n_term_not_ack = workers(); _n_not_terminated = workers(); @@ -526,6 +526,7 @@ namespace Gecode { namespace Search { namespace Par { if (!solutions.empty()) { // No search needs to be done, take leftover solution Space* s = solutions.pop(); + end = EndReason::NotEnded; m_search.release(); return s; } @@ -533,6 +534,7 @@ namespace Gecode { namespace Search { namespace Par { has_stopped.store(false, std::memory_order_release); // No more solutions? if (n_busy == 0) { + end = EndReason::Exhausted; m_search.release(); return nullptr; } @@ -553,6 +555,7 @@ namespace Gecode { namespace Search { namespace Par { if (!solutions.empty()) { // Report solution Space* s = solutions.pop(); + end = EndReason::NotEnded; m_search.release(); // Make workers wait again block(); @@ -560,6 +563,8 @@ namespace Gecode { namespace Search { namespace Par { } // No more solutions or stopped? if ((n_busy == 0) || has_stopped.load(std::memory_order_acquire)) { + // Workers that still have work have been stopped + end = (n_busy == 0) ? EndReason::Exhausted : EndReason::Limit; m_search.release(); // Make workers wait again block(); diff --git a/gecode/search/par/frontier.cpp b/gecode/search/par/frontier.cpp index 5977f8827f..38b001ae04 100644 --- a/gecode/search/par/frontier.cpp +++ b/gecode/search/par/frontier.cpp @@ -60,6 +60,7 @@ namespace Gecode { namespace Search { namespace Par { guidance(*o.guidance), best(guidance.sense), order(0), pending(heap), n_pending(0), runners(nullptr), active(0), running(false), shutdown(false), _stopped(false), _limited(false), + end(EndReason::NotEnded), batch(1), keyed(false) {} void @@ -335,6 +336,7 @@ namespace Gecode { namespace Search { namespace Par { std::rethrow_exception(error); if (_limited) { _stopped = true; + end = EndReason::Incomplete; return nullptr; } _stopped = false; @@ -348,7 +350,14 @@ namespace Gecode { namespace Search { namespace Par { continue; if (error) std::rethrow_exception(error); - return solution.release(); + Space* s = solution.release(); + if (s != nullptr) + end = EndReason::NotEnded; + else if (_limited) + end = EndReason::Incomplete; + else + end = _stopped ? EndReason::Limit : EndReason::Exhausted; + return s; } } @@ -358,16 +367,10 @@ namespace Gecode { namespace Search { namespace Par { return stat; } - bool - Frontier::stopped(void) const { - Support::Lock lock(mutex); - return _stopped; - } - - bool - Frontier::limited(void) const { + EndReason + Frontier::end_reason(void) const { Support::Lock lock(mutex); - return _limited; + return end; } void @@ -392,6 +395,7 @@ namespace Gecode { namespace Search { namespace Par { solution.reset(); order = 0; _stopped = _limited = false; + end = EndReason::NotEnded; error = nullptr; stat.reset(); initialize(s,false); diff --git a/gecode/search/par/frontier.hh b/gecode/search/par/frontier.hh index 23a5075a5a..63fd89a35f 100644 --- a/gecode/search/par/frontier.hh +++ b/gecode/search/par/frontier.hh @@ -110,6 +110,8 @@ namespace Gecode { namespace Search { namespace Par { unsigned int active; /// Whether search is running, being shut down, stopped, or limited bool running, shutdown, _stopped, _limited; + /// Why the last call to next() returned no solution + EndReason end; /// First exception thrown by a worker std::exception_ptr error; @@ -160,10 +162,8 @@ namespace Gecode { namespace Search { namespace Par { Space* next(void) override; /// Return statistics Search::Statistics statistics(void) const override; - /// Whether search has been stopped - bool stopped(void) const override; - /// Whether search stopped at the width or frontier limit - bool limited(void) const override; + /// Return why the last call to next() returned no solution + EndReason end_reason(void) const override; /// Constrain future solutions to be better than \a s void constrain(const Space& s) override; /// Reset engine to restart at space \a s diff --git a/gecode/search/par/pbs.hh b/gecode/search/par/pbs.hh index fb180a69f0..e8881e7b75 100644 --- a/gecode/search/par/pbs.hh +++ b/gecode/search/par/pbs.hh @@ -102,10 +102,8 @@ namespace Gecode { namespace Search { namespace Par { Asset(PBS* p, Engine* e, Stop* so); /// Return statistics of asset Statistics statistics(void) const; - /// Check whether asset has been stopped - bool stopped(void) const; - /// Check whether asset stopped at a local limit - bool limited(void) const; + /// Return why the last call to next() of the asset returned no solution + EndReason end_reason(void) const; /// Return the completion terminator virtual Support::Terminator* terminator(void) const; /// Wait for the asset to complete its current run @@ -181,8 +179,10 @@ namespace Gecode { namespace Search { namespace Par { unsigned int n_active; /// Whether an asset has been stopped std::atomic asset_stop; - /// Whether an asset stopped at a local limit + /// Whether an asset finished without exhausting its search space bool incomplete; + /// Why the last call to next() returned no solution + EndReason end; /// Shared stop flag std::atomic tostop; /// Collect solutions in this @@ -214,8 +214,8 @@ namespace Gecode { namespace Search { namespace Par { virtual Space* next(void); /// Return statistics virtual Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Constrain future solutions to be better than \a b virtual void constrain(const Space& b); /// Destructor diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index 73c28cff03..cabcaeaeff 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -152,18 +152,9 @@ namespace Gecode { namespace Search { namespace Par { return engine->statistics(); } template - forceinline bool - Asset::stopped(void) const { - return engine->stopped(); - } - template - forceinline bool - Asset::limited(void) const { -#ifdef GECODE_HAS_EXPERIMENTAL - return engine->limited(); -#else - return false; -#endif + forceinline EndReason + Asset::end_reason(void) const { + return engine->end_reason(); } template forceinline Support::Terminator* @@ -199,7 +190,7 @@ namespace Gecode { namespace Search { namespace Par { const Statistics& stat0) : stat(stat0), assets(heap.alloc*>(n)), n_assets(n), n_active(n), - asset_stop(false), incomplete(false), tostop(false), n_busy(0) { + asset_stop(false), incomplete(false), end(EndReason::NotEnded), tostop(false), n_busy(0) { // Initialize assets for (unsigned int i=0U; i(this,engines[i],stops[i]); @@ -229,15 +220,15 @@ namespace Gecode { namespace Search { namespace Par { tostop.store(true, std::memory_order_release); wake = true; } - } else if (asset->stopped() && !asset->limited()) { + } else if (asset->end_reason() == EndReason::Limit) { if (!tostop.load(std::memory_order_acquire)) { asset_stop.store(true, std::memory_order_release); tostop.store(true, std::memory_order_release); wake = true; } } else { - // The asset is done or stopped at a local limit (then search is incomplete) - if (asset->limited()) + // The asset is done , without a proof if it is incomplete + if (asset->end_reason() == EndReason::Incomplete) incomplete = true; // Move asset to inactive unsigned int i=0; @@ -324,9 +315,6 @@ namespace Gecode { namespace Search { namespace Par { // Invariant all assets are idle! assert(n_busy == 0); - if (solutions.empty() && (n_active == 0) && incomplete) - asset_stop.store(true, std::memory_order_release); - // Report a stored failure before broadcasting a solution, which could // call into the failed asset and replace the original exception. if (failure != nullptr) { @@ -340,7 +328,12 @@ namespace Gecode { namespace Search { namespace Par { // Process solutions if (solutions.empty()) { s = nullptr; + if (asset_stop.load(std::memory_order_acquire)) + end = EndReason::Limit; + else + end = incomplete ? EndReason::Incomplete : EndReason::Exhausted; } else { + end = EndReason::NotEnded; Asset* r; s = solutions.get(r); if (Collect::best) { @@ -363,9 +356,9 @@ namespace Gecode { namespace Search { namespace Par { } template - bool - PBS::stopped(void) const { - return asset_stop.load(std::memory_order_acquire); + EndReason + PBS::end_reason(void) const { + return end; } template diff --git a/gecode/search/seq/cabs.hh b/gecode/search/seq/cabs.hh index f75e9ed056..05f41e2842 100644 --- a/gecode/search/seq/cabs.hh +++ b/gecode/search/seq/cabs.hh @@ -88,8 +88,8 @@ namespace Gecode { namespace Search { namespace Seq { Space* next(void); /// Return statistics Statistics statistics(void) const; - /// Whether search stopped at the width or frontier limit - bool limited(void) const; + /// Return why next() returned no solution, Incomplete at the width or frontier limit + EndReason end_reason(void) const; /// Constrain future solutions to be better than \a b void constrain(const Space& b); /// Reset engine to restart at space \a s diff --git a/gecode/search/seq/dead.cpp b/gecode/search/seq/dead.cpp index fa8ac10a07..550b87f350 100644 --- a/gecode/search/seq/dead.cpp +++ b/gecode/search/seq/dead.cpp @@ -43,6 +43,9 @@ namespace Gecode { namespace Search { namespace Seq { Tracer tracer; /// Statistics Statistics stat; + /// Why the last call to next() returned no solution + EndReason end; + public: /// Initialize Dead(const Options& o, const Statistics& stat0); @@ -50,15 +53,15 @@ namespace Gecode { namespace Search { namespace Seq { virtual Space* next(void); /// Return statistics virtual Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Delete virtual ~Dead(void); }; template Dead::Dead(const Options& o, const Statistics& stat0) - : tracer(o.tracer), stat(stat0) { + : tracer(o.tracer), stat(stat0) , end(EndReason::NotEnded) { tracer.engine(SearchTracer::EngineType::AOE, 1U); tracer.worker(); } @@ -66,13 +69,15 @@ namespace Gecode { namespace Search { namespace Seq { template Space* Dead::next(void) { + // The root has failed + end = EndReason::Exhausted; return nullptr; } template - bool - Dead::stopped(void) const { - return false; + EndReason + Dead::end_reason(void) const { + return end; } template diff --git a/gecode/search/seq/lds.hh b/gecode/search/seq/lds.hh index d95869b55a..35e42f91c9 100644 --- a/gecode/search/seq/lds.hh +++ b/gecode/search/seq/lds.hh @@ -112,8 +112,8 @@ namespace Gecode { namespace Search { namespace Seq { Space* root; /// Current discrepancy unsigned int d; - /// Solution found for current discrepancy - bool no_solution; + /// Why the last call to next() returned no solution + EndReason end; public: /// Initialize for space \a s with options \a o LDS(Space* s, const Options& o); @@ -125,8 +125,8 @@ namespace Gecode { namespace Search { namespace Seq { void constrain(const Space& b); /// Reset engine to restart at space \a s void reset(Space* s); - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Destructor virtual ~LDS(void); }; diff --git a/gecode/search/seq/lds.hpp b/gecode/search/seq/lds.hpp index 6a19404392..81f7331a75 100644 --- a/gecode/search/seq/lds.hpp +++ b/gecode/search/seq/lds.hpp @@ -276,7 +276,7 @@ namespace Gecode { namespace Search { namespace Seq { template forceinline LDS::LDS(Space* s, const Options& o) - : opt(o), e(opt), root(nullptr), d(0) { + : opt(o), e(opt), root(nullptr), d(0) , end(EndReason::NotEnded) { e.node = 1; if (s->status(e) == SS_FAILED) { e.fail++; @@ -295,10 +295,18 @@ namespace Gecode { namespace Search { namespace Seq { LDS::next(void) { while (true) { Space* s = e.next(opt); - if (s != nullptr) + if (s != nullptr) { + end = EndReason::NotEnded; return s; - if (((s == nullptr) && e.stopped()) || (++d > opt.d_l) || e.done()) + } + if (e.stopped()) { + end = EndReason::Limit; + break; + } + if ((++d > opt.d_l) || e.done()) { + end = EndReason::Exhausted; break; + } if (d == opt.d_l) { if (root != nullptr) e.reset(root,d); @@ -311,9 +319,9 @@ namespace Gecode { namespace Search { namespace Seq { } template - bool - LDS::stopped(void) const { - return e.stopped(); + EndReason + LDS::end_reason(void) const { + return end; } template @@ -327,6 +335,7 @@ namespace Gecode { namespace Search { namespace Seq { forceinline void LDS::reset(Space* s) { delete root; root=nullptr; d=0; + end = EndReason::NotEnded; // Reset the statistics first, so that a failed root is counted e.reset(nullptr,0); if (s == nullptr) diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index ef6cf4537b..008fdb8831 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -85,10 +85,8 @@ namespace Gecode { namespace Search { namespace Seq { Space* next(void); /// Return statistics of asset Statistics statistics(void) const; - /// Check whether asset has been stopped - bool stopped(void) const; - /// Check whether asset stopped at a local limit - bool limited(void) const; + /// Return why the last call to next() of the asset returned no solution + EndReason end_reason(void) const; /// Constrain with better solution \a b void constrain(const Space& b); /// Perform one run @@ -113,10 +111,10 @@ namespace Gecode { namespace Search { namespace Seq { unsigned int n_assets; /// Current asset to run unsigned int cur; - /// Whether an asset has been stopped - bool asset_stop; - /// Whether an asset stopped at a local limit + /// Whether an asset finished without exhausting its search space bool incomplete; + /// Why the last call to next() returned no solution + EndReason end; public: /// Initialize PBS(Engine** assets, Stop** stops, unsigned int n, @@ -125,8 +123,8 @@ namespace Gecode { namespace Search { namespace Seq { virtual Space* next(void); /// Return statistics virtual Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Constrain future solutions to be better than \a b virtual void constrain(const Space& b); /// Destructor diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index 4164993c59..3a234f7174 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -60,17 +60,9 @@ namespace Gecode { namespace Search { namespace Seq { Asset::statistics(void) const { return engine->statistics(); } - forceinline bool - Asset::stopped(void) const { - return engine->stopped(); - } - forceinline bool - Asset::limited(void) const { -#ifdef GECODE_HAS_EXPERIMENTAL - return engine->limited(); -#else - return false; -#endif + forceinline EndReason + Asset::end_reason(void) const { + return engine->end_reason(); } forceinline void Asset::constrain(const Space& b) { @@ -90,7 +82,7 @@ namespace Gecode { namespace Search { namespace Seq { const Search::Options& opt) : stat(stat0), slice(opt.slice), assets(heap.alloc(n)), n_assets(n), cur(0), - asset_stop(false), incomplete(false) { + incomplete(false), end(EndReason::NotEnded) { ssi.done = false; ssi.l = opt.slice; @@ -103,7 +95,6 @@ namespace Gecode { namespace Search { namespace Seq { template Space* PBS::next(void) { - asset_stop = false; unsigned int n_exhausted = 0; while (n_assets > 0) { ssi.done = false; @@ -120,18 +111,20 @@ namespace Gecode { namespace Search { namespace Seq { throw; } } + end = EndReason::NotEnded; return s; } - if (assets[cur].stopped() && !assets[cur].limited()) { + EndReason asset_end = assets[cur].end_reason(); + if (asset_end == EndReason::Limit) { if (ssi.done) { cur++; n_exhausted++; } else { - asset_stop = true; + end = EndReason::Limit; return nullptr; } } else { - // The asset is done or stopped at a local limit (then search is incomplete) - if (assets[cur].limited()) + // The asset is done, without a proof if it is incomplete + if (asset_end == EndReason::Incomplete) incomplete = true; // Kill the asset after saving the statistics stat += assets[cur].statistics(); @@ -149,14 +142,14 @@ namespace Gecode { namespace Search { namespace Seq { if (cur == n_assets) cur = 0; } - asset_stop = incomplete; + end = incomplete ? EndReason::Incomplete : EndReason::Exhausted; return nullptr; } template - bool - PBS::stopped(void) const { - return asset_stop; + EndReason + PBS::end_reason(void) const { + return end; } template diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index de656bee86..25696ea86a 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -79,9 +79,10 @@ namespace Gecode { namespace Search { namespace Seq { Space* RBS::next(void) { // A failed hub proves that no further solution exists - if (hub == nullptr) + if (hub == nullptr) { + end = EndReason::Exhausted; return nullptr; - m_stopped = false; + } if (restart) { restart = false; sslr++; @@ -94,6 +95,7 @@ namespace Gecode { namespace Search { namespace Seq { delete hub; hub = nullptr; e->reset(nullptr); + end = EndReason::Exhausted; return nullptr; } else if (r) { stop->update(e->statistics()); @@ -113,26 +115,29 @@ namespace Gecode { namespace Search { namespace Seq { restart = true; delete last; last = n->clone(); + end = EndReason::NotEnded; return n; - } else if ( (!complete && !e->stopped()) || - (e->stopped() && stop->enginestopped()) ) { + } + EndReason inner = e->end_reason(); + bool limit = inner == EndReason::Limit; + if ((!complete && !limit) || (limit && stop->enginestopped())) { // The engine must perform a true restart // The number of the restart has been incremented in the stop object - if (!complete && !e->stopped()) { + if (!complete && !limit) { /* * The engine might not have checked its stop object, for example * when the spoke failed at the root or a parallel engine had no * work. Without this check, the restarts might never stop. */ if (stop->meta_stop(e->statistics(),m_opt)) { - m_stopped = true; + end = EndReason::Limit; return nullptr; } stop->restart(); } sslr = 0; NoGoods& ng = hub_nogoods(); - MetaInfo mi(stop->restarts(),e->stopped() ? MetaInfo::RR_LIM : MetaInfo::RR_CMPL,sslr,e->statistics().fail,last,ng); + MetaInfo mi(stop->restarts(),limit ? MetaInfo::RR_LIM : MetaInfo::RR_CMPL,sslr,e->statistics().fail,last,ng); (void) hub->hub(mi); stop->nogood(ng.ng()); unsigned long long int nl = ++(*co); @@ -142,6 +147,7 @@ namespace Gecode { namespace Search { namespace Seq { delete hub; hub = nullptr; e->reset(nullptr); + end = EndReason::Exhausted; return nullptr; } Space* spoke = hub; @@ -150,6 +156,8 @@ namespace Gecode { namespace Search { namespace Seq { nogoods_valid = complete; e->reset(spoke); } else { + // A stop from above, or a complete spoke search has ended + end = inner; return nullptr; } } @@ -176,19 +184,16 @@ namespace Gecode { namespace Search { namespace Seq { e->constrain(b); } - bool - RBS::stopped(void) const { + EndReason + RBS::end_reason(void) const { /* - * What might happen during parallel search is that the - * engine has been stopped but the meta engine has not, so - * the meta engine does not perform a restart. However the - * invocation of next will do so and no restart will be - * missed. - * - * The engine may still report a stop when the hub failed during a - * restart after a limit. A failed hub is a proof, not a stop. + * What might happen during parallel search is that the engine has + * been stopped by the cutoff but the meta engine reports a limit, + * because the stop object of the meta engine also fired. The next + * invocation of next() then performs the restart, and no restart + * will be missed. */ - return (hub != nullptr) && (m_stopped || e->stopped()); + return end; } RBS::~RBS(void) { diff --git a/gecode/search/seq/rbs.hh b/gecode/search/seq/rbs.hh index 2c57744a59..4d930f2065 100755 --- a/gecode/search/seq/rbs.hh +++ b/gecode/search/seq/rbs.hh @@ -109,8 +109,8 @@ namespace Gecode { namespace Search { namespace Seq { bool restart; /// Whether the engine performs best solution search bool best; - /// Whether the stop object for the meta engine stopped a restart - bool m_stopped; + /// Why the last call to next() returned no solution + EndReason end; /// Return the no-goods of the last spoke search, valid in the hub NoGoods& hub_nogoods(void); public: @@ -128,8 +128,8 @@ namespace Gecode { namespace Search { namespace Seq { virtual Space* next(void); /// Return statistics virtual Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Constrain future solutions to be better than \a b virtual void constrain(const Space& b); /// Destructor diff --git a/gecode/search/seq/rbs.hpp b/gecode/search/seq/rbs.hpp index a4bacb56e5..ba428fd7ba 100755 --- a/gecode/search/seq/rbs.hpp +++ b/gecode/search/seq/rbs.hpp @@ -100,7 +100,7 @@ namespace Gecode { namespace Search { namespace Seq { : e(e0), hub(s), last(nullptr), co(opt.cutoff), stop(stop0), m_opt(opt.expand()), sslr(0), complete(complete0), nogoods_valid(complete0), restart(false), - best(best0), m_stopped(false) { + best(best0), end(EndReason::NotEnded) { stop->limit(stat,(*co)()); } diff --git a/gecode/search/support.hh b/gecode/search/support.hh index 6cdc0b2be4..bce378bc4d 100644 --- a/gecode/search/support.hh +++ b/gecode/search/support.hh @@ -65,6 +65,9 @@ namespace Gecode { namespace Search { protected: /// The worker to wrap into an engine Worker w; + /// Why the last call to next() returned no solution + EndReason end; + public: /// Initialization WorkerToEngine(Space* s, const Options& o); @@ -72,8 +75,8 @@ namespace Gecode { namespace Search { virtual Space* next(void); /// Return statistics virtual Search::Statistics statistics(void) const; - /// Check whether engine has been stopped - virtual bool stopped(void) const; + /// Return why the last call to next() returned no solution + virtual EndReason end_reason(void) const; /// Constrain future solutions to be better than \a b virtual void constrain(const Space& b); /// Reset engine to restart at space \a s @@ -92,11 +95,13 @@ namespace Gecode { namespace Search { template WorkerToEngine::WorkerToEngine(Space* s, const Options& o) - : Engine(o,1U), w(s,o) {} + : Engine(o,1U), w(s,o) , end(EndReason::NotEnded) {} template Space* WorkerToEngine::next(void) { - return w.next(); + Space* s = w.next(); + end = (s != nullptr) ? EndReason::NotEnded : w.end_reason(); + return s; } template Search::Statistics @@ -104,14 +109,15 @@ namespace Gecode { namespace Search { return w.statistics(); } template - bool - WorkerToEngine::stopped(void) const { - return w.stopped(); + EndReason + WorkerToEngine::end_reason(void) const { + return end; } template void WorkerToEngine::reset(Space* s) { w.reset(s); + end = EndReason::NotEnded; } template void diff --git a/gecode/search/worker.hh b/gecode/search/worker.hh index 892cd85a59..16118f8717 100644 --- a/gecode/search/worker.hh +++ b/gecode/search/worker.hh @@ -58,6 +58,8 @@ namespace Gecode { namespace Search { bool stop_seq(Options& o); /// Check whether engine has been stopped bool stopped(void) const; + /// Return why next() returned no solution: Limit if stopped, otherwise Exhausted + EndReason end_reason(void) const; /// Reset statistics with root depth \a d void reset(unsigned long int d=0); /// Record stack depth \a d @@ -102,6 +104,11 @@ namespace Gecode { namespace Search { return _stopped; } + forceinline EndReason + Worker::end_reason(void) const { + return _stopped ? EndReason::Limit : EndReason::Exhausted; + } + forceinline void Worker::reset(unsigned long int d) { Statistics::reset(); diff --git a/test/int/open-var-list.cpp b/test/int/open-var-list.cpp index 03a9f5920f..9f959ed039 100644 --- a/test/int/open-var-list.cpp +++ b/test/int/open-var-list.cpp @@ -274,7 +274,7 @@ namespace Test { namespace Int { }; while (Space* solution = engine->next()) record(static_cast(solution)); - if (!engine->stopped()) + if (engine->end_reason() != Search::EndReason::Limit) return false; // Deeper choices refer to positions absent from the restart root. engine->nogoods().post(root); diff --git a/test/nogoods.cpp b/test/nogoods.cpp index 2e819fd5f2..a7964ed174 100644 --- a/test/nogoods.cpp +++ b/test/nogoods.cpp @@ -242,7 +242,7 @@ namespace Test { while (true) { Model* s = static_cast(e->next()); delete s; - if (!e->stopped()) + if (e->end_reason() != Search::EndReason::Limit) break; // Add no-goods e->nogoods().post(*m); diff --git a/test/search.cpp b/test/search.cpp index 328c6c5b7b..39064b3447 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -89,6 +89,8 @@ namespace Test { using namespace Gecode; using namespace Gecode::Int; + using Gecode::Search::EndReason; + #ifdef GECODE_HAS_EXPERIMENTAL /// Explicit finite tree with prefix costs, admissible bounds, and ranks class TreeSpace : public Space { @@ -255,7 +257,7 @@ namespace Test { break; } } - return e.stopped() || (last == (*root.graph)[0].best); + return (e.end_reason() != EndReason::Exhausted) || (last == (*root.graph)[0].best); } /// Heuristic search engines on random trees @@ -287,7 +289,7 @@ namespace Test { E e(&root,o); if (!improving(e,root,step > 0U ? &stop : nullptr)) return false; - if ((o.max_width == 0UL) && e.stopped()) + if ((o.max_width == 0UL) && (e.end_reason() != EndReason::Exhausted)) return false; } return true; @@ -362,7 +364,7 @@ namespace Test { last = s->node().cost; delete s; } - return (last == 1) && e.stopped(); + return (last == 1) && (e.end_reason() == EndReason::Incomplete); } } heuristic_portfolio; #endif @@ -1071,7 +1073,8 @@ namespace Test { solutions++; delete solution; } - ok = !search.stopped() && (solutions == 2U) && (state.spoke_calls.load(std::memory_order_relaxed) >= 2U) && + ok = (search.end_reason() == EndReason::Exhausted) && (solutions == 2U) && + (state.spoke_calls.load(std::memory_order_relaxed) >= 2U) && (state.constrain_calls.load(std::memory_order_relaxed) >= 1U) && (state.nogood_handoffs.load(std::memory_order_relaxed) >= 1U); } @@ -1094,7 +1097,7 @@ namespace Test { Gecode::RBS search(m, o); delete m; HubSpokeDispatchSpace* solution = search.next(); - ok = (solution == nullptr) && search.stopped(); + ok = (solution == nullptr) && (search.end_reason() == EndReason::Limit); delete solution; } ok = ok && holds(rbs_state.live_spaces, 0U); @@ -1114,7 +1117,7 @@ namespace Test { Gecode::PBS search(m, o); delete m; HubSpokeDispatchSpace* solution = search.next(); - ok = ok && (solution == nullptr) && search.stopped(); + ok = ok && (solution == nullptr) && (search.end_reason() == EndReason::Limit); delete solution; } return ok && holds(pbs_state.live_spaces, 0U); @@ -1480,7 +1483,7 @@ namespace Test { bool complete = E::best ? (last && last->best() && ((node != 0U) || (solutions >= 2))) : (solutions == root.solutions()); - return ok && !engine.stopped() && complete; + return ok && (engine.end_reason() == EndReason::Exhausted) && complete; } #ifdef GECODE_HAS_EXPERIMENTAL template class E> @@ -1509,7 +1512,7 @@ namespace Test { std::future_status::timeout; control.request(threads); result.get(); - return ok && !engine.stopped() && (last == (*root.graph)[0].best); + return ok && (engine.end_reason() == EndReason::Exhausted) && (last == (*root.graph)[0].best); } #endif @@ -1570,7 +1573,7 @@ namespace Test { resizer.join(); best = (last != nullptr) && last->best(); delete last; - return !engine.stopped(); + return engine.end_reason() == EndReason::Exhausted; } public: WorkerControlConcurrentResize(void) @@ -2258,7 +2261,7 @@ namespace Test { if (value >= -1) return false; } - if (bounded->stopped()) + if (bounded->end_reason() != EndReason::Exhausted) return false; bounded.reset(); return missingFailure() && thrownFailure() && incomparableFailure(); @@ -2566,7 +2569,8 @@ namespace Test { (static_cast(s)->x.val().max() < 8.5); delete s; } - substep = substep && (found == 1) && !bab->stopped(); + substep = substep && (found == 1) && + (bab->end_reason() == EndReason::Exhausted); if (!substep) return false; #endif @@ -2709,11 +2713,11 @@ namespace Test { if (s != nullptr) { n--; delete s; } - if ((s == nullptr) && !dfs.stopped()) + if ((s == nullptr) && (dfs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } - return n == 0; + return (n == 0) && (dfs.end_reason() == EndReason::Exhausted); } }; @@ -2746,11 +2750,11 @@ namespace Test { if (s != nullptr) { n--; delete s; } - if ((s == nullptr) && !lds.stopped()) + if ((s == nullptr) && (lds.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } - return n == 0; + return (n == 0) && (lds.end_reason() == EndReason::Exhausted); } }; @@ -2790,11 +2794,11 @@ namespace Test { if (s != nullptr) { delete b; b=s; } - if ((s == nullptr) && !bab.stopped()) + if ((s == nullptr) && (bab.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } - bool ok = (b == nullptr) || b->best(); + bool ok = ((b == nullptr) || b->best()) && (bab.end_reason() == EndReason::Exhausted); delete b; return ok; } @@ -2838,12 +2842,12 @@ namespace Test { delete b; b = s; } } - if ((s == nullptr) && !rbs.stopped()) + if ((s == nullptr) && (rbs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } if (htc == HTC_NONE) - return n == 0; + return (n == 0) && (rbs.end_reason() == EndReason::Exhausted); bool ok = improving && (b != nullptr) && b->best(); delete b; return ok; @@ -2897,7 +2901,7 @@ namespace Test { best = s->x[0].val(); delete s; } - return !rbs.stopped() && (best == 0); + return (rbs.end_reason() == EndReason::Exhausted) && (best == 0); } }; @@ -2965,10 +2969,12 @@ namespace Test { } Gecode::Search::Statistics s = rbs.statistics(); // The failures of the last spoke search are counted once - if (rbs.stopped() || (s.restart != 1U) || (s.fail < 2U) || + if ((rbs.end_reason() != EndReason::Exhausted) || + (s.restart != 1U) || (s.fail < 2U) || ((t == 1U) && (s.fail != 2U))) return false; - if ((rbs.next() != nullptr) || rbs.stopped() || + if ((rbs.next() != nullptr) || + (rbs.end_reason() != EndReason::Exhausted) || (rbs.statistics().fail != s.fail) || (rbs.statistics().node != s.node)) return false; @@ -3023,7 +3029,7 @@ namespace Test { delete s; return false; } - return rbs.stopped() && (f.checks <= 1000) && + return (rbs.end_reason() == EndReason::Limit) && (f.checks <= 1000) && (rbs.statistics().fail >= 5); } public: @@ -3096,7 +3102,7 @@ namespace Test { } }; - /// A search exhausted when it reaches a failure limit is not stopped + /// A search exhausted when it reaches a failure limit is exhausted class ExhaustedAtLimit : public Base { template class Engine> static bool test(void) { @@ -3118,7 +3124,7 @@ namespace Test { Gecode::Search::Options o; o.stop = &l; Engine e(&root,o); - if ((e.next() != nullptr) || e.stopped()) + if ((e.next() != nullptr) || (e.end_reason() != EndReason::Exhausted)) return false; } // Restarts at that limit post no no-goods and would repeat forever @@ -3129,7 +3135,8 @@ namespace Test { o.nogoods_limit = 128U; o.cutoff = Gecode::Search::Cutoff::constant(f-1); Gecode::RBS rbs(&root,o); - if ((rbs.next() != nullptr) || rbs.stopped()) + if ((rbs.next() != nullptr) || + (rbs.end_reason() != EndReason::Exhausted)) return false; } return true; @@ -3203,7 +3210,7 @@ namespace Test { if (s != nullptr) { delete b; b=s; } - if ((s == nullptr) && !pbs.stopped()) + if ((s == nullptr) && (pbs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } @@ -3218,7 +3225,7 @@ namespace Test { if (s != nullptr) { n--; delete s; } - if ((s == nullptr) && !pbs.stopped()) + if ((s == nullptr) && (pbs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } @@ -3272,7 +3279,7 @@ namespace Test { if (s != nullptr) { delete b; b=s; } - if ((s == nullptr) && !pbs.stopped()) + if ((s == nullptr) && (pbs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } @@ -3294,7 +3301,7 @@ namespace Test { if (s != nullptr) { n--; delete s; } - if ((s == nullptr) && !pbs.stopped()) + if ((s == nullptr) && (pbs.end_reason() != EndReason::Limit)) break; f.limit(f.limit()+2); } @@ -3318,7 +3325,8 @@ namespace Test { sebs[0] = builder(Gecode::Search::Options::def); sebs[1] = builder(Gecode::Search::Options::def); Gecode::PBS pbs(&root,sebs,o); - return (pbs.next() == nullptr) && pbs.stopped() && (l.checks <= 1000); + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Limit) && (l.checks <= 1000); } public: PBSBuilderStop(void) : Base("Search::PBS::SEB::Stop") {} @@ -3410,7 +3418,8 @@ namespace Test { o.threads = threads; o.cutoff = Gecode::Search::Cutoff::geometric(1,2); Gecode::PBS pbs(&root,o); - return (pbs.next() == nullptr) && !pbs.stopped(); + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Exhausted); } public: PBSRestartCutoff(void) : Base("Search::PBS::RBS::Cutoff") {} @@ -3472,7 +3481,7 @@ namespace Test { delete s; return false; } - if (pbs.stopped()) + if (pbs.end_reason() != EndReason::Exhausted) return false; } return deleted == 1U; From 7569d1444ae0357c09cc9a90128ac70d7222833a Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 16:45:28 +0100 Subject: [PATCH 03/37] Report LDS at its discrepancy limit as incomplete Limited discrepancy search that reached its discrepancy limit reported the same end as a search that explored the whole tree, so its end could be taken as a proof. It now reports EndReason::Incomplete, and only a search whose last probe explored every alternative reports EndReason::Exhausted. --- changelog.in | 7 +++++++ docs/gecode-7-migration.md | 8 ++++---- gecode/search.hh | 14 +++++--------- gecode/search/seq/lds.hpp | 7 ++++++- test/search.cpp | 24 ++++++++++++++++++++++++ 5 files changed, 46 insertions(+), 14 deletions(-) diff --git a/changelog.in b/changelog.in index 158af60945..eb75df8f0d 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,13 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Report limited discrepancy search at its discrepancy limit as incomplete. + [ENTRY] Module: search What: change diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 3886e665af..ad8a0ce8a5 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -90,10 +90,10 @@ enum class Gecode::Search::EndReason : unsigned char { `Exhausted` means that the engine explored everything it was asked to explore: there is no further solution, and the last solution of a branch-and-bound search is optimal. `Incomplete` means that the engine ended -on its own without that proof, for example CABS at its width limit. Calling -`next()` again does not continue an incomplete search. `Limit` means that a -stop object stopped the engine, and calling `next()` again continues the -search. +on its own without that proof, for example limited discrepancy search at its +discrepancy limit or CABS at its width limit. Calling `next()` again does not +continue an incomplete search. `Limit` means that a stop object stopped the +engine, and calling `next()` again continues the search. Code that used `!stopped()` as a proof, such as reporting optimality, should test for `EndReason::Exhausted`. Code that resumes a search after a limit diff --git a/gecode/search.hh b/gecode/search.hh index 0e51e75a38..09e70edcbc 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1115,8 +1115,8 @@ namespace Gecode { namespace Search { Exhausted, /** * Search finished without exhausting its search space, for example - * at the width limit of CABS. There may be further solutions, but - * calling next() again finds none. + * at the discrepancy limit of LDS or the width limit of CABS. There + * may be further solutions, but calling next() again finds none. */ Incomplete, /// A stop object stopped search, calling next() again resumes it @@ -1472,13 +1472,9 @@ namespace Gecode { * Search::Options::d_l discrepancies, allowing more discrepancies in each * iteration, starting from none. * - * When next() returns nullptr and end_reason() returns - * Search::EndReason::Exhausted, either the search tree has been explored - * completely, or the discrepancy limit has been reached while parts of - * the tree are still unexplored. The engine - * does not report which: a search that finds no (further) solution only - * proves that none exists if no path of the tree has more discrepancies - * than the limit. + * When the search tree has choices that need more discrepancies than + * the limit in Search::Options::d_l, end_reason() returns + * Search::EndReason::Incomplete once the search ends. * * \ingroup TaskModelSearch */ diff --git a/gecode/search/seq/lds.hpp b/gecode/search/seq/lds.hpp index 81f7331a75..257b63e19e 100644 --- a/gecode/search/seq/lds.hpp +++ b/gecode/search/seq/lds.hpp @@ -303,10 +303,15 @@ namespace Gecode { namespace Search { namespace Seq { end = EndReason::Limit; break; } - if ((++d > opt.d_l) || e.done()) { + if (e.done()) { end = EndReason::Exhausted; break; } + // Choices with more discrepancies than the limit were not explored + if (++d > opt.d_l) { + end = EndReason::Incomplete; + break; + } if (d == opt.d_l) { if (root != nullptr) e.reset(root,d); diff --git a/test/search.cpp b/test/search.cpp index 39064b3447..03e9aefafa 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -3150,6 +3150,30 @@ namespace Test { ExhaustedAtLimit exhausted_at_limit; + /// LDS reports an incomplete search at its discrepancy limit + class LDSIncomplete : public Base { + static EndReason end_reason(unsigned int d_l) { + NoSolution root; + Gecode::Search::Options o; + o.d_l = d_l; + Gecode::LDS lds(&root,o); + if (NoSolution* s = lds.next()) { + delete s; + return EndReason::NotEnded; + } + return lds.end_reason(); + } + public: + LDSIncomplete(void) : Base("Search::LDS::Incomplete") {} + bool run(void) override { + return (end_reason(0) == EndReason::Incomplete) && + (end_reason(1) == EndReason::Incomplete) && + (end_reason(100) == EndReason::Exhausted); + } + }; + + LDSIncomplete lds_incomplete; + /// Space for relaxing class RelaxSpace : public Gecode::Space { public: From 6f2a5af4ef90152969d0da9dfb01b7be6a3e0ce8 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 17:06:24 +0100 Subject: [PATCH 04/37] End a portfolio when an asset exhausts its search space An asset that exhausted its search space was dropped and the remaining assets continued. A portfolio next to an asset that never ends, such as restart-based large neighbourhood search, then ran until a stop object fired, although the exhausted asset had proven that no further solution exists. The portfolio now ends with EndReason::Exhausted. Every spoke is still taken to cover the search space of the hub. The check is kept in pbs_asset_proof() so that a spoke covering only part of the search space can be excluded once spokes declare their coverage. An asset ending without a proof is dropped as before, and a portfolio whose assets all end that way reports EndReason::Incomplete. --- changelog.in | 10 ++++++++++ gecode/search.hh | 7 +++++++ gecode/search/par/pbs.hh | 7 ++++--- gecode/search/par/pbs.hpp | 21 ++++++++++++-------- gecode/search/seq/pbs.hh | 3 +-- gecode/search/seq/pbs.hpp | 16 ++++++++++------ gecode/search/support.hh | 16 ++++++++++++++++ test/search.cpp | 40 ++++++++++++++++++++++++++++++++++++++- 8 files changed, 100 insertions(+), 20 deletions(-) diff --git a/changelog.in b/changelog.in index eb75df8f0d..44672e3157 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,16 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +End a portfolio when an asset exhausts its search space. +[MORE] +The exhausted asset proves that no further solution exists, so the other +assets no longer run until they are stopped. + [ENTRY] Module: search What: change diff --git a/gecode/search.hh b/gecode/search.hh index 09e70edcbc..b9e270797c 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1614,6 +1614,13 @@ namespace Gecode { * (see Cutoff::copy()). If the constructor throws an exception, the * caller keeps the cutoff. * + * The spoke of each asset is taken to cover the search space of the + * hub. When an asset exhausts its search space, the portfolio ends and + * end_reason() returns Search::EndReason::Exhausted. An asset that ends + * without exhausting its search space, such as LDS at its discrepancy + * limit, is dropped while the other assets continue. When every asset + * has been dropped, end_reason() returns Search::EndReason::Incomplete. + * * The class \a T can implement member functions * \code virtual bool hub(const MetaInfo& mi) \endcode * and diff --git a/gecode/search/par/pbs.hh b/gecode/search/par/pbs.hh index e8881e7b75..10581d2d23 100644 --- a/gecode/search/par/pbs.hh +++ b/gecode/search/par/pbs.hh @@ -39,6 +39,7 @@ #define GECODE_SEARCH_PAR_PBS_HH #include +#include #include #include @@ -179,8 +180,8 @@ namespace Gecode { namespace Search { namespace Par { unsigned int n_active; /// Whether an asset has been stopped std::atomic asset_stop; - /// Whether an asset finished without exhausting its search space - bool incomplete; + /// Whether an asset has proven that no further solution exists + bool exhausted; /// Why the last call to next() returned no solution EndReason end; /// Shared stop flag @@ -205,7 +206,7 @@ namespace Gecode { namespace Search { namespace Par { * - that entails, that locking is only needed inside next(). * - the assets 0..n_active-1 still might not have exhausted their * search space. - * - the assets n_active..n_assets-1 have exhausted their search space. + * - the assets n_active..n_assets-1 have ended without a proof. */ public: /// Initialize diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index cabcaeaeff..4e99fcfdd4 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -190,7 +190,7 @@ namespace Gecode { namespace Search { namespace Par { const Statistics& stat0) : stat(stat0), assets(heap.alloc*>(n)), n_assets(n), n_active(n), - asset_stop(false), incomplete(false), end(EndReason::NotEnded), tostop(false), n_busy(0) { + asset_stop(false), exhausted(false), end(EndReason::NotEnded), tostop(false), n_busy(0) { // Initialize assets for (unsigned int i=0U; i(this,engines[i],stops[i]); @@ -226,11 +226,13 @@ namespace Gecode { namespace Search { namespace Par { tostop.store(true, std::memory_order_release); wake = true; } + } else if (pbs_asset_proof(asset->end_reason())) { + // Stop the other assets, no further solution exists + exhausted = true; + tostop.store(true, std::memory_order_release); + wake = true; } else { - // The asset is done , without a proof if it is incomplete - if (asset->end_reason() == EndReason::Incomplete) - incomplete = true; - // Move asset to inactive + // The asset ended without a proof, move it to inactive unsigned int i=0; while (assets[i] != asset) i++; @@ -290,7 +292,7 @@ namespace Gecode { namespace Search { namespace Par { if (solutions.empty()) asset_stop.store(false, std::memory_order_release); while (solutions.empty() && (n_active > 0) && (failure == nullptr) && - !asset_stop.load(std::memory_order_acquire)) { + !exhausted && !asset_stop.load(std::memory_order_acquire)) { // Clear the internal stop used to interrupt sibling assets tostop.store(false, std::memory_order_release); @@ -328,10 +330,13 @@ namespace Gecode { namespace Search { namespace Par { // Process solutions if (solutions.empty()) { s = nullptr; - if (asset_stop.load(std::memory_order_acquire)) + if (exhausted) + end = EndReason::Exhausted; + else if (asset_stop.load(std::memory_order_acquire)) end = EndReason::Limit; else - end = incomplete ? EndReason::Incomplete : EndReason::Exhausted; + // All assets ended without a proof + end = EndReason::Incomplete; } else { end = EndReason::NotEnded; Asset* r; diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index 008fdb8831..ddcfe2db4f 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -35,6 +35,7 @@ #define GECODE_SEARCH_SEQ_PBS_HH #include +#include namespace Gecode { namespace Search { namespace Seq { @@ -111,8 +112,6 @@ namespace Gecode { namespace Search { namespace Seq { unsigned int n_assets; /// Current asset to run unsigned int cur; - /// Whether an asset finished without exhausting its search space - bool incomplete; /// Why the last call to next() returned no solution EndReason end; public: diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index 3a234f7174..bd32fca5a7 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -82,7 +82,7 @@ namespace Gecode { namespace Search { namespace Seq { const Search::Options& opt) : stat(stat0), slice(opt.slice), assets(heap.alloc(n)), n_assets(n), cur(0), - incomplete(false), end(EndReason::NotEnded) { + end(EndReason::NotEnded) { ssi.done = false; ssi.l = opt.slice; @@ -95,6 +95,9 @@ namespace Gecode { namespace Search { namespace Seq { template Space* PBS::next(void) { + // An asset has proven that no further solution exists + if (end == EndReason::Exhausted) + return nullptr; unsigned int n_exhausted = 0; while (n_assets > 0) { ssi.done = false; @@ -122,11 +125,11 @@ namespace Gecode { namespace Search { namespace Seq { end = EndReason::Limit; return nullptr; } + } else if (pbs_asset_proof(asset_end)) { + end = EndReason::Exhausted; + return nullptr; } else { - // The asset is done, without a proof if it is incomplete - if (asset_end == EndReason::Incomplete) - incomplete = true; - // Kill the asset after saving the statistics + // The asset ended without a proof, kill it after saving the statistics stat += assets[cur].statistics(); assets[cur].~Asset(); assets[cur] = assets[--n_assets]; @@ -142,7 +145,8 @@ namespace Gecode { namespace Search { namespace Seq { if (cur == n_assets) cur = 0; } - end = incomplete ? EndReason::Incomplete : EndReason::Exhausted; + // All assets ended without a proof + end = EndReason::Incomplete; return nullptr; } diff --git a/gecode/search/support.hh b/gecode/search/support.hh index bce378bc4d..7e5d7abd4c 100644 --- a/gecode/search/support.hh +++ b/gecode/search/support.hh @@ -59,6 +59,22 @@ namespace Gecode { namespace Search { forceinline Space* snapshot(Space* s, const Options& o); + /** + * \brief Whether a portfolio asset that ended for reason \a r proves that + * the hub has no further solution + * + * The spoke of every asset is taken to cover the search space of the + * hub, so an exhausted asset ends the portfolio with a proof. A spoke + * that covers only part of the search space, such as a fragment for + * large neighbourhood search, must not end the portfolio when it is + * exhausted: once spokes can declare their coverage, this is where it is + * taken into account. + */ + forceinline bool + pbs_asset_proof(EndReason r) { + return r == EndReason::Exhausted; + } + /// Virtualize a worker to an engine template class WorkerToEngine : public Engine { diff --git a/test/search.cpp b/test/search.cpp index 03e9aefafa..6440443932 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -364,7 +364,7 @@ namespace Test { last = s->node().cost; delete s; } - return (last == 1) && (e.end_reason() == EndReason::Incomplete); + return (last == 1) && (e.end_reason() == EndReason::Exhausted); } } heuristic_portfolio; #endif @@ -3365,6 +3365,44 @@ namespace Test { PBSBuilderStop pbs_builder_stop; + /// An exhausted asset ends a portfolio whose other asset never ends + class PBSExhaustedAsset : public Base { + /// Stop after many checks, in case the portfolio does not end + class ManyChecks : public Gecode::Search::Stop { + public: + /// Number of checks + std::atomic checks{0UL}; + bool stop(const Gecode::Search::Statistics&, + const Gecode::Search::Options&) override { + return ++checks > 10000000UL; + } + }; + static bool test(unsigned int threads) { + FailingSpoke root; + ManyChecks l; + Gecode::Search::Options a; + a.cutoff = Gecode::Search::Cutoff::constant(1); + Gecode::SEBs sebs(2); + sebs[0] = Gecode::rbs(a); + sebs[1] = Gecode::dfs(); + Gecode::Search::Options o; + o.threads = threads; + o.stop = &l; + Gecode::PBS pbs(&root,sebs,o); + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Exhausted) && + (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Exhausted); + } + public: + PBSExhaustedAsset(void) : Base("Search::PBS::ExhaustedAsset") {} + bool run(void) override { + return test(1U) && test(2U); + } + }; + + PBSExhaustedAsset pbs_exhausted_asset; + /// A copy of a cutoff generator continues its sequence independently class CutoffCopy : public Base { /// Check that a copy of \a c continues as \a c, then delete \a c From c44af9e49412a4ddf5d8467702e786635831f0e8 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 17:11:25 +0100 Subject: [PATCH 05/37] Run every asset of a parallel portfolio Parallel portfolio search ran only as many assets, or engine builders, as it had threads and silently dropped the others. A portfolio of three assets with two threads therefore ran two of them. Every asset now runs in its own thread, and the threads are divided among the assets with at least one thread for each asset's engine, as in sequential portfolios. --- changelog.in | 11 +++++++++++ gecode/search.hh | 16 ++++++++++------ gecode/search/pbs.hpp | 25 ++++++------------------- test/search.cpp | 6 +++--- 4 files changed, 30 insertions(+), 28 deletions(-) diff --git a/changelog.in b/changelog.in index 44672e3157..38870137ce 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,17 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Run every asset of a parallel portfolio, also when there are more assets +than threads. +[MORE] +Parallel portfolio search ran only as many assets as it had threads and +silently dropped the others. + [ENTRY] Module: search What: bug diff --git a/gecode/search.hh b/gecode/search.hh index b9e270797c..98f16ba38e 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1600,8 +1600,11 @@ namespace Gecode { * \brief Meta engine using a portfolio of search engines * * The engine will run a portfolio with a number of assets as defined - * by the options \a o. The engine supports parallel execution of - * assets by using the number of threads as defined by the options. + * by the options \a o. With more than one thread in \a o, every asset + * runs in its own thread, also when there are more assets than threads, + * and the threads are divided evenly among the assets, with at least + * one thread for each asset. With one thread, the assets take turns in + * slices of failures (see Search::Options::slice). * For best-solution assets, a solution replaces the incumbent only if * Space::compare reports SpaceComparison::Better. * An external worker control in \a o is supported only for a single @@ -1649,8 +1652,9 @@ namespace Gecode { * * The outer options must not contain a worker control. Each builder can * instead supply a distinct control for its underlying engine. - * In parallel PBS, the outer thread count limits how many builders run, - * in array order; each builder's options set its own engine's thread count. + * In parallel PBS, the engine of every builder runs in its own thread, + * also when there are more builders than outer threads; each builder's + * options set its own engine's thread count. * * With experimental search, AStar and CABS builders can be used * together with BAB builders. @@ -1666,8 +1670,8 @@ namespace Gecode { * \brief Run a portfolio of search engines * * The engine will run a portfolio with a number of assets as defined - * by the options \a o. The engine supports parallel execution of - * assets by using the number of threads as defined by the options. + * by the options \a o. See PBS for how the assets use the threads in + * \a o. * An external worker control is supported only when \a o selects one * asset. PBS does not implement worker-allocation policy. * diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index 96c6ee48b5..759158e2d2 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -64,16 +64,6 @@ namespace Gecode { namespace Search { throw WorkerControlInUse("PBS::PBS"); } - /// Return the number of explicit builders admitted by this portfolio - forceinline int - pbsadmitted(const SEBs& sebs, const Options& opt) { -#ifdef GECODE_HAS_THREADS - if (opt.threads > 1.0) - return std::min(static_cast(opt.threads),sebs.size()); -#endif - return sebs.size(); - } - /// Validate worker-control placement for an explicit portfolio forceinline void pbscontrol(const SEBs& sebs, const Options& opt) { @@ -84,8 +74,7 @@ namespace Gecode { namespace Search { #else const bool parallel = false; #endif - int admitted = pbsadmitted(sebs,opt); - for (int i=0; ioptions().worker_control; if (!x.engaged()) continue; @@ -327,11 +316,10 @@ namespace Gecode { namespace Search { opt.clone = true; Region r; - // Limit the number of assets to the number of threads - unsigned int n_assets = std::min(static_cast(opt.threads), - opt.assets); + // Run every asset in its own thread, even with fewer threads than assets + unsigned int n_assets = opt.assets; // Redistribute additional threads to assets - opt.threads = floor(opt.threads / static_cast(n_assets)); + opt.threads = std::max(floor(opt.threads / static_cast(n_assets)), 1.0); WrapTraceRecorder::engine(opt.tracer, SearchTracer::EngineType::PBS, n_assets); @@ -375,9 +363,8 @@ namespace Gecode { namespace Search { const Search::Statistics& stat, Options& opt, bool best) { Region r; - // Limit the number of assets to the number of threads - int n_assets = std::min(static_cast(opt.threads), - sebs.size()); + // Run every asset in its own thread, even with fewer threads than assets + int n_assets = sebs.size(); WrapTraceRecorder::engine(opt.tracer, SearchTracer::EngineType::PBS, diff --git a/test/search.cpp b/test/search.cpp index 6440443932..5fcf812d89 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -1245,8 +1245,8 @@ namespace Test { case Scenario::PbsParallel: return pbs(3, 3, 1, 3, 7); case Scenario::PbsParallelThreadLimit: - // Parallel PBS runs only as many assets as it has threads. - return pbs(3, 2, 1, 2, 3); + // Parallel PBS runs all assets, also with fewer threads. + return pbs(3, 2, 1, 3, 7); case Scenario::PbsDefaultHubRemovesBranchers: return pbs_default_hub_removes_branchers(); case Scenario::RbsNoGoodsResetOwnership: @@ -3242,7 +3242,7 @@ namespace Test { delete b; return ok; } else { - int n = ((t > 1) ? std::min(a,t) : a) * m->solutions(); + int n = a * m->solutions(); delete m; while (true) { Model* s = pbs.next(); From cfef78f92c9b98c83b9729ed01c5eea30987697e Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 17:29:58 +0100 Subject: [PATCH 06/37] Check the portfolio stop object with portfolio-wide statistics The stop object in the options of a portfolio was checked for each asset with the statistics of that asset. A failure limit of n for a portfolio of k assets therefore allowed up to k * n failures, and with engine builders the portfolio stop object was checked like a builder's. The portfolio stop object is now checked with the sum of the statistics of all assets. A sequential portfolio adds the statistics of the other assets before running an asset. A parallel portfolio records the latest statistics of each asset under a mutex, only when the portfolio has a stop object. The stop objects of engine builders are still checked with the statistics of their engine. --- changelog.in | 11 +++++++++ docs/gecode-7-migration.md | 17 +++++++++++++ gecode/search.hh | 13 ++++++++-- gecode/search/par/pbs.cpp | 12 ++++++++- gecode/search/par/pbs.hh | 44 ++++++++++++++++++++++++++++++--- gecode/search/par/pbs.hpp | 24 +++++++++++++++--- gecode/search/pbs.hpp | 4 +-- gecode/search/seq/pbs.cpp | 2 +- gecode/search/seq/pbs.hh | 10 +++++++- gecode/search/seq/pbs.hpp | 4 +++ test/search.cpp | 50 ++++++++++++++++++++++++++++++++++++++ 11 files changed, 177 insertions(+), 14 deletions(-) diff --git a/changelog.in b/changelog.in index 38870137ce..919da9fcc4 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,17 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Check the stop object of a portfolio with the statistics of the whole +portfolio. +[MORE] +It was checked for each asset with the statistics of that asset. See +docs/gecode-7-migration.md. + [ENTRY] Module: search What: change diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index ad8a0ce8a5..6d549d1455 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -98,3 +98,20 @@ engine, and calling `next()` again continues the search. Code that used `!stopped()` as a proof, such as reporting optimality, should test for `EndReason::Exhausted`. Code that resumes a search after a limit should test for `EndReason::Limit`. + +## Portfolio stop objects see the whole portfolio + +The stop object in the options of `PBS` is now checked with the statistics +of the whole portfolio, the sum over all assets. In Gecode 6, it was checked +for each asset with the statistics of that asset, so a failure limit of +`n` for a portfolio of `k` assets allowed up to `k * n` failures. A stop +object that should limit each asset on its own belongs in the options of an +engine builder: + +```cpp +Gecode::Search::Options a, b; +a.stop = &dfs_stop; +b.stop = &lds_stop; +Gecode::SEBs sebs({Gecode::dfs(a), Gecode::lds(b)}); +Gecode::PBS engine(model, sebs, portfolio_options); +``` diff --git a/gecode/search.hh b/gecode/search.hh index 98f16ba38e..92d23324fa 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1605,6 +1605,14 @@ namespace Gecode { * and the threads are divided evenly among the assets, with at least * one thread for each asset. With one thread, the assets take turns in * slices of failures (see Search::Options::slice). + * + * The stop object in \a o is checked with the statistics of the whole + * portfolio, that is, the sum of the statistics of all assets. With + * parallel assets, these are the statistics that the workers pass to + * their stop objects. When the stop object stops search, end_reason() + * returns Search::EndReason::Limit and calling next() again resumes all + * assets. + * * For best-solution assets, a solution replaces the incumbent only if * Space::compare reports SpaceComparison::Better. * An external worker control in \a o is supported only for a single @@ -1647,8 +1655,9 @@ namespace Gecode { /** * Initialize with engine builders \a sebs * - * The stop object of \a o is checked for each builder's engine with the - * statistics of that engine, as is the stop object of the builder. + * The stop object of \a o is checked with the statistics of the whole + * portfolio, the stop object of a builder with the statistics of the + * engine it builds. * * The outer options must not contain a worker control. Each builder can * instead supply a distinct control for its underlying engine. diff --git a/gecode/search/par/pbs.cpp b/gecode/search/par/pbs.cpp index 2c8e06f0a8..072c01568c 100644 --- a/gecode/search/par/pbs.cpp +++ b/gecode/search/par/pbs.cpp @@ -40,11 +40,21 @@ namespace Gecode { namespace Search { namespace Par { + Statistics + PortfolioStatistics::update(unsigned int i, const Statistics& s) { + Support::Lock lock(m); + stat[i + 1] = s; + Statistics t; + for (unsigned int j = 0U; j < n; j++) + t += stat[j]; + return t; + } + bool PortfolioStop::stop(const Statistics& s, const Options& o) { return tostop->load(std::memory_order_acquire) || ((so != nullptr) && so->stop(s,o)) || - ((po != nullptr) && po->stop(s,o)); + ((po != nullptr) && po->stop(ps->update(asset,s),o)); } void diff --git a/gecode/search/par/pbs.hh b/gecode/search/par/pbs.hh index 10581d2d23..7fd267c9de 100644 --- a/gecode/search/par/pbs.hh +++ b/gecode/search/par/pbs.hh @@ -45,7 +45,38 @@ namespace Gecode { namespace Search { namespace Par { - /// Stop object used for controlling assets in a portfolio + /** + * \brief Statistics of the assets of a parallel portfolio + * + * Each asset records the statistics that its engine passes to its stop + * object. For an asset with a parallel engine, these are the statistics + * of the worker that checks the stop object. + */ + class GECODE_SEARCH_EXPORT PortfolioStatistics { + private: + /// Mutex for access + Support::Mutex m; + /// Number of entries: propagating the model and one for each asset + unsigned int n; + /// Statistics of propagating the model followed by those of each asset + Statistics* stat; + + public: + /// Initialize with statistics \a s of propagating the model for \a n assets + PortfolioStatistics(const Statistics& s, unsigned int n); + /// Record statistics \a s of asset \a i and return those of the portfolio + Statistics update(unsigned int i, const Statistics& s); + /// Delete + ~PortfolioStatistics(void); + }; + + /** + * \brief Stop object used for controlling assets in a portfolio + * + * The stop object of the asset is checked with the statistics of the + * asset, the stop object of the portfolio with the statistics of the + * whole portfolio. + */ class GECODE_SEARCH_EXPORT PortfolioStop : public Stop { private: /// The stop object for the assets @@ -56,11 +87,16 @@ namespace Gecode { namespace Search { namespace Par { WorkerControl worker_control; /// Whether search must be stopped std::atomic* tostop; + /// Statistics of the portfolio + PortfolioStatistics* ps; + /// Index of the asset + unsigned int asset; public: /// Initialize with asset stop \a so, portfolio stop \a po, and \a control PortfolioStop(Stop* so, Stop* po, const WorkerControl& control); - /// Set pointer to shared \a tostop variable - void share(std::atomic* ts); + /// Share stop flag \a ts and statistics \a ps of the portfolio with asset \a i + void share(std::atomic* ts, PortfolioStatistics* ps, + unsigned int i); /// Return true if portfolio engine must be stopped virtual bool stop(const Statistics& s, const Options& o); /// Wake workers so that a paused asset can observe the portfolio stop @@ -172,6 +208,8 @@ namespace Gecode { namespace Search { namespace Par { protected: /// Statistics of propagating the model Statistics stat; + /// Statistics of the portfolio for its stop object + PortfolioStatistics portfolio_stat; /// Asset engines Asset** assets; /// Number of asset engines diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index 4e99fcfdd4..cfab0f9d2f 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -131,14 +131,29 @@ namespace Gecode { namespace Search { namespace Par { } + forceinline + PortfolioStatistics::PortfolioStatistics(const Statistics& s, unsigned int n0) + : n(n0 + 1), stat(heap.alloc(n0 + 1)) { + stat[0] = s; + } + + forceinline + PortfolioStatistics::~PortfolioStatistics(void) { + heap.free(stat, n); + } + forceinline PortfolioStop::PortfolioStop(Stop* so0, Stop* po0, const WorkerControl& control) - : so(so0), po(po0), worker_control(control), tostop(nullptr) {} + : so(so0), po(po0), worker_control(control), tostop(nullptr), + ps(nullptr), asset(0U) {} forceinline void - PortfolioStop::share(std::atomic* ts) { + PortfolioStop::share(std::atomic* ts, PortfolioStatistics* ps0, + unsigned int i) { tostop = ts; + ps = ps0; + asset = i; } @@ -188,13 +203,14 @@ namespace Gecode { namespace Search { namespace Par { forceinline PBS::PBS(Engine** engines, Stop** stops, unsigned int n, const Statistics& stat0) - : stat(stat0), assets(heap.alloc*>(n)), + : stat(stat0), portfolio_stat(stat0,n), + assets(heap.alloc*>(n)), n_assets(n), n_active(n), asset_stop(false), exhausted(false), end(EndReason::NotEnded), tostop(false), n_busy(0) { // Initialize assets for (unsigned int i=0U; i(this,engines[i],stops[i]); - static_cast(stops[i])->share(&tostop); + static_cast(stops[i])->share(&tostop,&portfolio_stat,i); } } diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index 759158e2d2..34990d41a7 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -237,7 +237,7 @@ namespace Gecode { namespace Search { Space* unowned_hub = hub; try { for (unsigned int i=0U; i spoke((i == n_assets-1) ? hub : hub->clone()); if (spoke.get() == hub) @@ -335,7 +335,7 @@ namespace Gecode { namespace Search { Space* unowned_hub = hub; try { for (unsigned int i=0U; i spoke((i == n_assets-1) ? hub : hub->clone()); if (spoke.get() == hub) diff --git a/gecode/search/seq/pbs.cpp b/gecode/search/seq/pbs.cpp index 1e79557f76..87624239c0 100644 --- a/gecode/search/seq/pbs.cpp +++ b/gecode/search/seq/pbs.cpp @@ -38,7 +38,7 @@ namespace Gecode { namespace Search { namespace Seq { bool PortfolioStop::stop(const Statistics& s, const Options& o) { if (((so != nullptr) && so->stop(s,o)) || - ((po != nullptr) && po->stop(s,o))) { + ((po != nullptr) && po->stop(ssi->others + s,o))) { ssi->done = false; return true; } diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index ddcfe2db4f..43cf6cd13c 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -46,9 +46,17 @@ namespace Gecode { namespace Search { namespace Seq { bool done; /// The current failure limit, incremented for each slice unsigned long long int l; + /// Statistics of the portfolio except for the running asset + Statistics others; }; - /// Stop object used for controlling assets in a portfolio + /** + * \brief Stop object used for controlling assets in a portfolio + * + * The stop object of the asset is checked with the statistics of the + * asset, the stop object of the portfolio with the statistics of the + * whole portfolio. + */ class GECODE_SEARCH_EXPORT PortfolioStop : public Stop { private: /// The stop object for the assets diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index bd32fca5a7..70a0add84b 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -101,6 +101,10 @@ namespace Gecode { namespace Search { namespace Seq { unsigned int n_exhausted = 0; while (n_assets > 0) { ssi.done = false; + ssi.others = stat; + for (unsigned int i=0U; i(a); + sebs[1] = Gecode::rbs(b); + Gecode::PBS pbs(&root,sebs,o); + if ((pbs.next() != nullptr) || + (pbs.end_reason() != EndReason::Limit)) + return false; + s = pbs.statistics(); + } else { + o.assets = 2; + o.cutoff = Gecode::Search::Cutoff::constant(1); + Gecode::PBS pbs(&root,o); + if ((pbs.next() != nullptr) || + (pbs.end_reason() != EndReason::Limit)) + return false; + s = pbs.statistics(); + } + // Checked for each asset, the limit would allow twice the failures + return (s.fail > limit) && (s.fail < limit + limit / 2U); + } + public: + PBSPortfolioStop(void) : Base("Search::PBS::PortfolioStop") {} + bool run(void) override { + for (unsigned int t : {1U,2U}) + for (bool builders : {false,true}) + if (!test(t,builders)) + return false; + return true; + } + }; + + PBSPortfolioStop pbs_portfolio_stop; + /// A copy of a cutoff generator continues its sequence independently class CutoffCopy : public Base { /// Check that a copy of \a c continues as \a c, then delete \a c From 66750e7943b602fc82aad5285916e05175d115d1 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sat, 14 Nov 2026 18:00:05 +0100 Subject: [PATCH 07/37] Park a portfolio asset whose own stop object fires When the stop object of an engine builder stopped its engine, the whole portfolio stopped and reported a limit, although the other assets could still have found solutions or exhausted the search space. The portfolio stop objects now record which stop object stopped an asset. An asset stopped by its own stop object is parked and the other assets continue. The portfolio reports EndReason::Limit when only parked assets remain, or when its own stop object fires, and parked assets resume with the next call to next(). --- changelog.in | 11 +++++ gecode/search.hh | 12 ++++-- gecode/search/par/pbs.cpp | 16 +++++-- gecode/search/par/pbs.hh | 21 +++++++-- gecode/search/par/pbs.hpp | 89 ++++++++++++++++++++++++++++++--------- gecode/search/seq/pbs.cpp | 11 +++-- gecode/search/seq/pbs.hh | 14 ++++-- gecode/search/seq/pbs.hpp | 57 +++++++++++++++++++------ gecode/search/support.hh | 9 ++++ test/search.cpp | 60 ++++++++++++++++++++++++++ 10 files changed, 249 insertions(+), 51 deletions(-) diff --git a/changelog.in b/changelog.in index 919da9fcc4..cb902901ab 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,17 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Keep the other assets of a portfolio running when the stop object of an +engine builder stops its engine. +[MORE] +The whole portfolio stopped instead. The stopped asset is now parked until +the next call to next(). + [ENTRY] Module: search What: change diff --git a/gecode/search.hh b/gecode/search.hh index 92d23324fa..8fdbda55a9 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1103,8 +1103,10 @@ namespace Gecode { namespace Search { * ended without such a proof. * * A meta engine (restart-based or portfolio search) reports Limit - * only for a stop object installed above it, not for its own - * cutoffs, slices, or the stop objects of its assets. + * for a stop object installed above it, not for its own cutoffs or + * slices. A portfolio also reports Limit when the stop objects of + * its assets have parked every asset that remains (see PBS), and + * calling next() again resumes them. * * \ingroup TaskModelSearch */ @@ -1657,7 +1659,11 @@ namespace Gecode { * * The stop object of \a o is checked with the statistics of the whole * portfolio, the stop object of a builder with the statistics of the - * engine it builds. + * engine it builds. When the stop object of a builder stops its + * engine, that asset is parked while the other assets continue. When + * only parked assets remain, end_reason() returns + * Search::EndReason::Limit, and the parked assets resume with the + * next call to next(). * * The outer options must not contain a worker control. Each builder can * instead supply a distinct control for its underlying engine. diff --git a/gecode/search/par/pbs.cpp b/gecode/search/par/pbs.cpp index 072c01568c..94ef331ef0 100644 --- a/gecode/search/par/pbs.cpp +++ b/gecode/search/par/pbs.cpp @@ -52,9 +52,19 @@ namespace Gecode { namespace Search { namespace Par { bool PortfolioStop::stop(const Statistics& s, const Options& o) { - return tostop->load(std::memory_order_acquire) || - ((so != nullptr) && so->stop(s,o)) || - ((po != nullptr) && po->stop(ps->update(asset,s),o)); + if (tostop->load(std::memory_order_acquire)) { + _cause.store(PortfolioStopCause::Interrupt, std::memory_order_relaxed); + return true; + } + if ((po != nullptr) && po->stop(ps->update(asset,s),o)) { + _cause.store(PortfolioStopCause::Portfolio, std::memory_order_relaxed); + return true; + } + if ((so != nullptr) && so->stop(s,o)) { + _cause.store(PortfolioStopCause::Asset, std::memory_order_relaxed); + return true; + } + return false; } void diff --git a/gecode/search/par/pbs.hh b/gecode/search/par/pbs.hh index 7fd267c9de..a91559e679 100644 --- a/gecode/search/par/pbs.hh +++ b/gecode/search/par/pbs.hh @@ -91,6 +91,8 @@ namespace Gecode { namespace Search { namespace Par { PortfolioStatistics* ps; /// Index of the asset unsigned int asset; + /// Which stop object stopped the asset + std::atomic _cause; public: /// Initialize with asset stop \a so, portfolio stop \a po, and \a control PortfolioStop(Stop* so, Stop* po, const WorkerControl& control); @@ -101,6 +103,10 @@ namespace Gecode { namespace Search { namespace Par { virtual bool stop(const Statistics& s, const Options& o); /// Wake workers so that a paused asset can observe the portfolio stop void wake(void); + /// Forget which stop object stopped the asset + void reset(void); + /// Return which stop object stopped the asset + PortfolioStopCause cause(void) const; /// Signal whether search must be stopped void stop(bool s); /// Whether search must be stopped @@ -134,6 +140,8 @@ namespace Gecode { namespace Search { namespace Par { Engine* engine; /// Stop object Stop* stop; + /// Whether the stop object of the asset stopped it during the current call to next() + bool _parked; public: /// Initialize with portfolio \a p, engine \a e, and its stop object \a so Asset(PBS* p, Engine* e, Stop* so); @@ -149,6 +157,12 @@ namespace Gecode { namespace Search { namespace Par { void wake(void); /// Constrain with better solution \a b void constrain(const Space& b); + /// Return which stop object stopped the asset + PortfolioStopCause cause(void) const; + /// Set whether the asset is parked + void parked(bool p); + /// Whether the asset is parked + bool parked(void) const; /// Perform one run virtual void run(void); /// Delete asset @@ -216,8 +230,8 @@ namespace Gecode { namespace Search { namespace Par { unsigned int n_assets; /// Number of active asset engines unsigned int n_active; - /// Whether an asset has been stopped - std::atomic asset_stop; + /// Whether the stop object of the portfolio has stopped an asset + std::atomic portfolio_stop; /// Whether an asset has proven that no further solution exists bool exhausted; /// Why the last call to next() returned no solution @@ -243,7 +257,8 @@ namespace Gecode { namespace Search { namespace Par { * - n_busy is always zero outside the next() function. * - that entails, that locking is only needed inside next(). * - the assets 0..n_active-1 still might not have exhausted their - * search space. + * search space, the parked ones among them are not run until the + * next call to next(). * - the assets n_active..n_assets-1 have ended without a proof. */ public: diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index cfab0f9d2f..9d435e141f 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -145,12 +145,21 @@ namespace Gecode { namespace Search { namespace Par { forceinline PortfolioStop::PortfolioStop(Stop* so0, Stop* po0, const WorkerControl& control) - : so(so0), po(po0), worker_control(control), tostop(nullptr), - ps(nullptr), asset(0U) {} + : so(so0), po(po0), worker_control(control), tostop(nullptr), ps(nullptr), asset(0U), + _cause(PortfolioStopCause::None) {} forceinline void - PortfolioStop::share(std::atomic* ts, PortfolioStatistics* ps0, - unsigned int i) { + PortfolioStop::reset(void) { + _cause.store(PortfolioStopCause::None, std::memory_order_relaxed); + } + + forceinline PortfolioStopCause + PortfolioStop::cause(void) const { + return _cause.load(std::memory_order_relaxed); + } + + forceinline void + PortfolioStop::share(std::atomic* ts, PortfolioStatistics* ps0, unsigned int i) { tostop = ts; ps = ps0; asset = i; @@ -160,7 +169,7 @@ namespace Gecode { namespace Search { namespace Par { template forceinline Asset::Asset(PBS* p, Engine* e, Stop* so) - : Support::Runnable(false), portfolio(p), engine(e), stop(so) {} + : Support::Runnable(false), portfolio(p), engine(e), stop(so), _parked(false) {} template forceinline Statistics Asset::statistics(void) const { @@ -192,6 +201,21 @@ namespace Gecode { namespace Search { namespace Par { engine->constrain(b); } template + forceinline PortfolioStopCause + Asset::cause(void) const { + return static_cast(stop)->cause(); + } + template + forceinline void + Asset::parked(bool p) { + _parked = p; + } + template + forceinline bool + Asset::parked(void) const { + return _parked; + } + template Asset::~Asset(void) { delete engine; delete stop; @@ -206,7 +230,7 @@ namespace Gecode { namespace Search { namespace Par { : stat(stat0), portfolio_stat(stat0,n), assets(heap.alloc*>(n)), n_assets(n), n_active(n), - asset_stop(false), exhausted(false), end(EndReason::NotEnded), tostop(false), n_busy(0) { + portfolio_stop(false), exhausted(false), end(EndReason::NotEnded), tostop(false), n_busy(0) { // Initialize assets for (unsigned int i=0U; i(this,engines[i],stops[i]); @@ -237,10 +261,19 @@ namespace Gecode { namespace Search { namespace Par { wake = true; } } else if (asset->end_reason() == EndReason::Limit) { - if (!tostop.load(std::memory_order_acquire)) { - asset_stop.store(true, std::memory_order_release); + switch (asset->cause()) { + case PortfolioStopCause::Interrupt: + // The asset runs again with the next round + break; + case PortfolioStopCause::Portfolio: + portfolio_stop.store(true, std::memory_order_release); tostop.store(true, std::memory_order_release); wake = true; + break; + default: + // The stop object of the asset stopped it, the others continue + asset->parked(true); + break; } } else if (pbs_asset_proof(asset->end_reason())) { // Stop the other assets, no further solution exists @@ -289,6 +322,7 @@ namespace Gecode { namespace Search { namespace Par { try { Space* s; do { + static_cast(stop)->reset(); s = engine->next(); } while (!portfolio->report(this,s)); } catch (...) { @@ -305,10 +339,21 @@ namespace Gecode { namespace Search { namespace Par { m.release(); std::rethrow_exception(f); } - if (solutions.empty()) - asset_stop.store(false, std::memory_order_release); - while (solutions.empty() && (n_active > 0) && (failure == nullptr) && - !exhausted && !asset_stop.load(std::memory_order_acquire)) { + if (solutions.empty()) { + portfolio_stop.store(false, std::memory_order_release); + // Resume the assets that their own stop objects stopped + for (unsigned int i=0U; iparked(false); + } + while (solutions.empty() && (failure == nullptr) && + !exhausted && !portfolio_stop.load(std::memory_order_acquire)) { + unsigned int n_run = 0; + for (unsigned int i=0U; iparked()) + n_run++; + if (n_run == 0) + break; + // Clear the internal stop used to interrupt sibling assets tostop.store(false, std::memory_order_release); @@ -316,14 +361,15 @@ namespace Gecode { namespace Search { namespace Par { assert(n_busy == 0); assert(!tostop.load(std::memory_order_acquire)); - // Run all active assets - n_busy = n_active; - for (unsigned int i=0U; iwait(); - Support::Thread::run(assets[i]); - } + // Run all active assets that are not parked + n_busy = n_run; + for (unsigned int i=0U; iparked()) { + // Consume the previous completion before reusing this asset. The + // initial signal handles the first submission. + assets[i]->wait(); + Support::Thread::run(assets[i]); + } m.release(); // Wait for all assets to become idle idle.wait(); @@ -348,7 +394,8 @@ namespace Gecode { namespace Search { namespace Par { s = nullptr; if (exhausted) end = EndReason::Exhausted; - else if (asset_stop.load(std::memory_order_acquire)) + else if (portfolio_stop.load(std::memory_order_acquire) || (n_active > 0)) + // Stopped by the portfolio stop object, or only parked assets remain end = EndReason::Limit; else // All assets ended without a proof diff --git a/gecode/search/seq/pbs.cpp b/gecode/search/seq/pbs.cpp index 87624239c0..64c7909a35 100644 --- a/gecode/search/seq/pbs.cpp +++ b/gecode/search/seq/pbs.cpp @@ -37,13 +37,16 @@ namespace Gecode { namespace Search { namespace Seq { bool PortfolioStop::stop(const Statistics& s, const Options& o) { - if (((so != nullptr) && so->stop(s,o)) || - ((po != nullptr) && po->stop(ssi->others + s,o))) { - ssi->done = false; + if ((po != nullptr) && po->stop(ssi->others + s,o)) { + ssi->cause = PortfolioStopCause::Portfolio; + return true; + } + if ((so != nullptr) && so->stop(s,o)) { + ssi->cause = PortfolioStopCause::Asset; return true; } if (s.fail >= ssi->l) { - ssi->done = true; + ssi->cause = PortfolioStopCause::Slice; return true; } return false; diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index 43cf6cd13c..87bafc751d 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -42,8 +42,8 @@ namespace Gecode { namespace Search { namespace Seq { /// Shared stop information class SharedStopInfo { public: - /// Whether search stopped because the slice is done - bool done; + /// Which stop object stopped the running asset + PortfolioStopCause cause; /// The current failure limit, incremented for each slice unsigned long long int l; /// Statistics of the portfolio except for the running asset @@ -81,6 +81,8 @@ namespace Gecode { namespace Search { namespace Seq { Engine* engine; /// Stop object Stop* stop; + /// Whether the stop object of the asset stopped it during the current call to next() + bool _parked; public: /// Default constructor Asset(void); @@ -98,8 +100,12 @@ namespace Gecode { namespace Search { namespace Seq { EndReason end_reason(void) const; /// Constrain with better solution \a b void constrain(const Space& b); - /// Perform one run - void run(void); + /// Park the asset after its stop object stopped it + void park(void); + /// Resume a parked asset + void resume(void); + /// Whether the asset is parked + bool parked(void) const; /// Delete asset ~Asset(void); }; diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index 70a0add84b..b7a66a9f35 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -47,7 +47,7 @@ namespace Gecode { namespace Search { namespace Seq { forceinline Asset::Asset(void) - : engine(nullptr), stop(nullptr) {} + : engine(nullptr), stop(nullptr), _parked(false) {} forceinline void Asset::init(Engine* e, Stop* so) { engine = e; stop = so; @@ -68,8 +68,19 @@ namespace Gecode { namespace Search { namespace Seq { Asset::constrain(const Space& b) { engine->constrain(b); } - forceinline - Asset::~Asset(void) { + forceinline void + Asset::park(void) { + _parked = true; + } + forceinline void + Asset::resume(void) { + _parked = false; + } + forceinline bool + Asset::parked(void) const { + return _parked; + } + forceinline Asset::~Asset(void) { delete engine; delete stop; } @@ -83,7 +94,7 @@ namespace Gecode { namespace Search { namespace Seq { : stat(stat0), slice(opt.slice), assets(heap.alloc(n)), n_assets(n), cur(0), end(EndReason::NotEnded) { - ssi.done = false; + ssi.cause = PortfolioStopCause::None; ssi.l = opt.slice; for (unsigned int i=0U; i 0) { - ssi.done = false; + if (assets[cur].parked()) { + if (++cur == n_assets) + cur = 0; + continue; + } + ssi.cause = PortfolioStopCause::None; ssi.others = stat; for (unsigned int i=0U; i 0) && (n_parked == n_assets)) { + // Only parked assets remain, they resume with the next call + end = EndReason::Limit; + return nullptr; + } + if (n_sliced + n_parked == n_assets) { + n_sliced = 0; // Increment by one slice ssi.l += slice; } - if (cur == n_assets) - cur = 0; } // All assets ended without a proof end = EndReason::Incomplete; diff --git a/gecode/search/support.hh b/gecode/search/support.hh index 7e5d7abd4c..44042cb16c 100644 --- a/gecode/search/support.hh +++ b/gecode/search/support.hh @@ -75,6 +75,15 @@ namespace Gecode { namespace Search { return r == EndReason::Exhausted; } + /// Which stop object stopped an asset of a portfolio + enum class PortfolioStopCause : unsigned char { + None, ///< No stop object has stopped the asset + Slice, ///< The asset used up its slice of a sequential portfolio + Interrupt, ///< Another asset of a parallel portfolio interrupted the asset + Asset, ///< The stop object of the asset + Portfolio, ///< The stop object of the portfolio + }; + /// Virtualize a worker to an engine template class WorkerToEngine : public Engine { diff --git a/test/search.cpp b/test/search.cpp index 854b213ca2..a87186b52b 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -3453,6 +3453,66 @@ namespace Test { PBSPortfolioStop pbs_portfolio_stop; + /// An asset stopped by its own stop object is parked while the others continue + class PBSParkedAsset : public Base { + /// Stop object that always stops + class AlwaysStop : public Gecode::Search::Stop { + public: + bool stop(const Gecode::Search::Statistics&, + const Gecode::Search::Options&) override { + return true; + } + }; + /// Whether the other asset continues and exhausts the search space + static bool others_continue(unsigned int threads) { + NoSolution root; + AlwaysStop always; + Gecode::Search::Options a; + a.stop = &always; + Gecode::SEBs sebs(2); + sebs[0] = Gecode::dfs(a); + sebs[1] = Gecode::dfs(); + Gecode::Search::Options o; + o.threads = threads; + Gecode::PBS pbs(&root,sebs,o); + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Exhausted); + } + /// Whether parked assets resume with the next call + static bool resume(unsigned int threads) { + NoSolution root; + Gecode::Search::FailStop f0(0), f1(0); + Gecode::Search::Options a0, a1; + a0.stop = &f0; + a1.stop = &f1; + Gecode::SEBs sebs(2); + sebs[0] = Gecode::dfs(a0); + sebs[1] = Gecode::lds(a1); + Gecode::Search::Options o; + o.threads = threads; + Gecode::PBS pbs(&root,sebs,o); + unsigned int limits = 0; + while ((pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Limit)) { + if (++limits > 1000) + return false; + f0.limit(f0.limit() + 1); + f1.limit(f1.limit() + 1); + } + return (limits > 0) && (pbs.end_reason() == EndReason::Exhausted); + } + public: + PBSParkedAsset(void) : Base("Search::PBS::ParkedAsset") {} + bool run(void) override { + for (unsigned int t : {1U,2U}) + if (!others_continue(t) || !resume(t)) + return false; + return true; + } + }; + + PBSParkedAsset pbs_parked_asset; + /// A copy of a cutoff generator continues its sequence independently class CutoffCopy : public Base { /// Check that a copy of \a c continues as \a c, then delete \a c From b32b2f6a744d75c5d4015f61d7ea2f35a37775d8 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Sun, 15 Nov 2026 02:03:28 +0100 Subject: [PATCH 08/37] Replace MetaInfo with hub and spoke contexts The meta search hooks now take contexts and answer through them: void hub(HubContext& hc); void spoke(SpokeContext& sc); Both contexts tell the hook which engine calls it (MetaEngine), why (MetaEvent), the episode, the asset and the number of assets, the last solution, the statistics and the no-goods of the episode that ended. hub() sets a MetaDecision (Restart or Continue), Restart by default. spoke() declares a SpokeCoverage (Full or Partial), Full by default. MetaInfo, the Boolean results and the deleted master() and slave() declarations are removed, and with them the compile tests for the deleted declarations. The engines call the hooks at the same points and with the same semantics as before. Restart-based search calls hub() after a solution, at the cutoff, and when a Partial spoke is exhausted or ends without a proof, honours Continue only after a solution, and ends after a Full spoke is exhausted or ends without a proof. Episodes count from zero and increase for every new spoke. Portfolio search calls hub() once with Start and spoke() for each asset. FlatZinc derives the on_restart status from the event and declares its on_restart and LNS spokes Partial. The examples, tests, documentation and migration notes use the new hooks. --- changelog.in | 8 +- docs/gecode-7-migration.md | 80 ++++-- examples/crossword.cpp | 15 +- examples/photo.cpp | 14 +- examples/qcp.cpp | 9 +- gecode/flatzinc.hh | 4 +- gecode/flatzinc/flatzinc.cpp | 52 ++-- gecode/kernel/core.cpp | 28 +- gecode/kernel/core.hpp | 507 ++++++++++++++++++++++++----------- gecode/search.hh | 36 +-- gecode/search/pbs.hpp | 36 ++- gecode/search/rbs.cpp | 6 +- gecode/search/rbs.hpp | 18 +- gecode/search/seq/rbs.cpp | 151 ++++++----- gecode/search/seq/rbs.hh | 27 +- gecode/search/seq/rbs.hpp | 12 +- test/search.cpp | 265 +++++++++--------- 17 files changed, 768 insertions(+), 500 deletions(-) diff --git a/changelog.in b/changelog.in index cb902901ab..84dfb8aeb9 100755 --- a/changelog.in +++ b/changelog.in @@ -154,10 +154,12 @@ Module: search What: change Rank: major [DESCRIPTION] -Rename the meta-search Space hooks master() and slave() to hub() and spoke(). +Replace the meta-search Space hooks master() and slave() and the class +MetaInfo by hub(HubContext&) and spoke(SpokeContext&). [MORE] -There are no compatibility aliases. An old override marked override fails to -compile; one without it is never called. See docs/gecode-7-migration.md. +hub() sets a MetaDecision and spoke() declares a SpokeCoverage instead of +returning a Boolean. There are no compatibility aliases, also not for the +FlatZincSpace override of slave(). See docs/gecode-7-migration.md. [ENTRY] Module: search diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 6d549d1455..9027192fa6 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -1,8 +1,8 @@ # Gecode 7 migration notes -## Meta-search hooks: master() and slave() are now hub() and spoke() +## Meta-search hooks: hub() and spoke() take contexts -Rename the overrides. Their signatures and return values are unchanged: +The hooks `master()` and `slave()` and the class `MetaInfo` are replaced: ```cpp // Gecode 6 @@ -10,33 +10,71 @@ bool master(const Gecode::MetaInfo& mi) override; bool slave(const Gecode::MetaInfo& mi) override; // Gecode 7 -bool hub(const Gecode::MetaInfo& mi) override; -bool spoke(const Gecode::MetaInfo& mi) override; +void hub(Gecode::HubContext& hc) override; +void spoke(Gecode::SpokeContext& sc) override; ``` -There are no compatibility aliases. An old override marked `override` fails -to compile; one without it compiles but is never called. Restart-based search (RBS) and portfolio-based search -(PBS) call the renamed hooks at the same points and with the same defaults -as before. - -The hooks run on these spaces: - -- RBS calls `hub()` after each solution and at each restart. The hub - carries the last solution and the no-goods from one restart to the next. - RBS calls `spoke()` on each new spoke, a clone of the hub, including the - first. The default `hub()` constrains the hub with the last solution, if - any, and posts the no-goods. -- PBS calls `hub()` once, then calls `spoke()` with the asset number on the - spoke of each asset, the hub or a clone of it. The default `hub()` - removes all branchers, so `spoke()` must post the branching of each - asset. +There are no compatibility aliases. `MetaInfo` no longer exists, so an old +override fails to compile. Restart-based search (RBS) calls `hub()` on its +hub and `spoke()` on each spoke, a clone of the hub that one episode +searches. Portfolio-based search (PBS) calls `hub()` once and `spoke()` on +the spoke of each asset. + +Both contexts provide what `MetaInfo` provided: + +| Gecode 6 | Gecode 7 | +|----------------------------------------|----------------------------------------------------| +| `mi.type()`: `RESTART`, `PORTFOLIO` | `engine()`: `MetaEngine::Restart`, `Portfolio` | +| `mi.reason()`: `RR_INIT` | `event()`: `MetaEvent::Start` | +| `RR_SOL` | `MetaEvent::Solution` | +| `RR_LIM` | `MetaEvent::Limit` | +| `RR_CMPL` | `MetaEvent::Exhausted` | +| (none) | `MetaEvent::Incomplete`, such as LDS at its limit | +| `RR_NO` (portfolio) | `MetaEvent::Start` | +| `mi.restart()` | `episode()` | +| `mi.fail()` | `statistics().fail` | +| `mi.solution()` | none: `event()` tells whether there was a solution | +| `mi.last()` | `last()` | +| `mi.nogoods()` | `nogoods()` | +| `mi.asset()` | `asset()`, and `assets()` for their number | + +`episode()` counts from zero and increases by one for every new spoke, +whatever ended the previous episode. In `hub()` it is the episode that +ended, in `spoke()` the episode that starts. `statistics()` holds the +statistics of the episode that ended. `last()` is only valid while the hook +runs; clone the solution to keep it. + +The return values become explicit decisions: + +| Gecode 6 | Gecode 7 | +|----------------------------------------|--------------------------------------------------------| +| `master()` returns `true` | `hc.decision(MetaDecision::Restart)`, the default | +| `master()` returns `false` after a solution | `hc.decision(MetaDecision::Continue)` | +| `slave()` returns `true` | nothing, `SpokeCoverage::Full` is the default | +| `slave()` returns `false` | `sc.coverage(SpokeCoverage::Partial)` | + +RBS honours `Continue` only after `MetaEvent::Solution`, just as it ignored +`false` from `master()` after other events. To prove that no further +solution exists, fail the hub. + +The coverage tells the engine what a spoke covers of the hub's search space: + +- `Full`: the spoke adds only branching and constraints that the hub + implies. Exhausting it is a proof. +- `Partial`: the spoke searches part of the hub's search space, such as a + large neighbourhood. Exhausting it is no proof, and the no-goods + recorded while searching it do not reach `hub()`. + +The engine trusts the declared coverage. A spoke that declares more than it +covers, such as `Full` for a spoke that removes solutions, gives undefined +results. The examples show typical overrides: - `examples/crossword.cpp`: a `hub()` that posts no-goods and continues after a solution instead of restarting. - `examples/photo.cpp`: an RBS `spoke()` that relaxes the last solution for - large neighbourhood search. + large neighbourhood search and declares `SpokeCoverage::Partial`. - `examples/qcp.cpp`: a PBS `spoke()` that posts a different branching for each asset. diff --git a/examples/crossword.cpp b/examples/crossword.cpp index 729d3bb116..dc97dc74a2 100755 --- a/examples/crossword.cpp +++ b/examples/crossword.cpp @@ -281,13 +281,14 @@ class Crossword : public Script { << ((a == 0) ? "<=" : ">") << " " << n; } - /// Do not perform a restart when a solution is found - bool hub(const MetaInfo& mi) { - if (mi.type() == MetaInfo::RESTART) - // Post no-goods - mi.nogoods().post(*this); - // Do not perform a restart if a solution has been found - return false; + /// Post no-goods, and do not perform a restart when a solution is found + void hub(HubContext& hc) { + if (hc.engine() == MetaEngine::Restart) { + hc.nogoods().post(*this); + if (hc.event() == MetaEvent::Solution) + hc.decision(MetaDecision::Continue); + } + // For portfolio search, keep the branchers } /// Constructor for cloning \a s diff --git a/examples/photo.cpp b/examples/photo.cpp index 15a19e3dd1..bd9e94c8de 100644 --- a/examples/photo.cpp +++ b/examples/photo.cpp @@ -128,15 +128,13 @@ class Photo : public IntMinimizeScript { break; } } - /// Spoke function for restarts - bool spoke(const MetaInfo& mi) { - if ((mi.type() == MetaInfo::RESTART) && - (mi.restart() > 0) && (p > 0.0)) { - const Photo& l = static_cast(*mi.last()); + /// Relax the last solution for large neighbourhood search + void spoke(SpokeContext& sc) { + if ((sc.engine() == MetaEngine::Restart) && + (sc.last() != nullptr) && (p > 0.0)) { + const Photo& l = static_cast(*sc.last()); relax(*this, pos, l.pos, rnd, p); - return false; - } else { - return true; + sc.coverage(SpokeCoverage::Partial); } } /// Constructor for cloning \a s diff --git a/examples/qcp.cpp b/examples/qcp.cpp index b74d144b3f..00f3b57348 100644 --- a/examples/qcp.cpp +++ b/examples/qcp.cpp @@ -211,11 +211,11 @@ class QCP : public Script { } } } - /// Spoke function for portfolio search - virtual bool spoke(const MetaInfo& mi) { - if (mi.type() == MetaInfo::PORTFOLIO) { + /// Post a different branching for each asset of portfolio search + virtual void spoke(SpokeContext& sc) { + if (sc.engine() == MetaEngine::Portfolio) { double tbf = opt.tbf(); - Rnd r(seeds[mi.asset() % n_seeds]); + Rnd r(seeds[sc.asset() % n_seeds]); switch (opt.branching()) { case BRANCH_SIZE: { @@ -244,7 +244,6 @@ class QCP : public Script { default: ; } } - return true; } /// Constructor for cloning \a s QCP(QCP& s) diff --git a/gecode/flatzinc.hh b/gecode/flatzinc.hh index 78b2039c63..534222f0f2 100755 --- a/gecode/flatzinc.hh +++ b/gecode/flatzinc.hh @@ -682,8 +682,8 @@ namespace Gecode { namespace FlatZinc { virtual void constrain(const Space& s); /// Copy function virtual Gecode::Space* copy(void); - /// Spoke function for restarts - virtual bool spoke(const MetaInfo& mi); + /// Spoke hook for restarts: on_restart and LNS spokes have partial coverage + virtual void spoke(SpokeContext& sc); /// \name AST to variable and value conversion //@{ diff --git a/gecode/flatzinc/flatzinc.cpp b/gecode/flatzinc/flatzinc.cpp index c9731cc107..d326496c4d 100644 --- a/gecode/flatzinc/flatzinc.cpp +++ b/gecode/flatzinc/flatzinc.cpp @@ -2131,14 +2131,13 @@ namespace Gecode { namespace FlatZinc { #endif } - bool - FlatZincSpace::spoke(const MetaInfo& mi) { - if (mi.type() == MetaInfo::RESTART) { + void + FlatZincSpace::spoke(SpokeContext& sc) { + if (sc.engine() == MetaEngine::Restart) { if (restart_data.initialized() && restart_data().mark_complete) { - // Fail the space + // Exhausting the failed spoke of full coverage proves completeness this->fail(); - // Return true to signal we are in the global search space - return true; + return; } bool ret = false; @@ -2146,7 +2145,7 @@ namespace Gecode { namespace FlatZinc { int base = 0; // Assign the sol_int values (use lb if no solution is known) - const FlatZincSpace* last = static_cast(mi.last()); + const FlatZincSpace* last = static_cast(sc.last()); assert(last == nullptr || last->on_restart_iv.size() == restart_data().on_restart_iv_sol); for (int i = 0; i < restart_data().on_restart_iv_sol; ++i) { IntVar& outVar = on_restart_iv[base + restart_data().on_restart_iv_sol + i]; @@ -2179,20 +2178,20 @@ namespace Gecode { namespace FlatZinc { if (restart_data().on_restart_status) { assert(base == on_restart_iv.size() - 1); IntVar& restart_status = on_restart_iv[base]; - switch(mi.reason()) { - case MetaInfo::RR_INIT: - assert(!mi.last()); + switch(sc.event()) { + case MetaEvent::Start: + assert(sc.last() == nullptr); rel(*this, restart_status, IRT_EQ, 1); // 1: START break; - case MetaInfo::RR_SOL: - assert(mi.solution() > 0); + case MetaEvent::Solution: + assert(sc.last() != nullptr); rel(*this, restart_status, IRT_EQ, 4); // 4: SAT break; - case MetaInfo::RR_CMPL: + case MetaEvent::Exhausted: rel(*this, restart_status, IRT_EQ, 3); // 3: UNSAT break; default: - assert(mi.reason() == MetaInfo::RR_LIM); + assert((sc.event() == MetaEvent::Limit) || (sc.event() == MetaEvent::Incomplete)); rel(*this, restart_status, IRT_EQ, 2); // 2: UNKNOWN break; } @@ -2213,7 +2212,7 @@ namespace Gecode { namespace FlatZinc { int base = 0; // Assign the sol_bool values (use lb if no solution is known) - const FlatZincSpace* last = static_cast(mi.last()); + const FlatZincSpace* last = static_cast(sc.last()); assert(last == nullptr || last->on_restart_bv.size() == restart_data().on_restart_bv_sol); for (int i = 0; i < restart_data().on_restart_bv_sol; ++i) { BoolVar& outVar = on_restart_bv[base + restart_data().on_restart_bv_sol + i]; @@ -2243,7 +2242,7 @@ namespace Gecode { namespace FlatZinc { int base = 0; // Assign the sol_set values (use lb if no solution is known) - const FlatZincSpace* last = static_cast(mi.last()); + const FlatZincSpace* last = static_cast(sc.last()); assert(last == nullptr || last->on_restart_sv.size() == restart_data().on_restart_sv_sol); for (int i = 0; i < restart_data().on_restart_sv_sol; ++i) { SetVar& outVar = on_restart_sv[base + restart_data().on_restart_sv_sol + i]; @@ -2275,7 +2274,7 @@ namespace Gecode { namespace FlatZinc { int base = 0; // Assign the sol_float values (use lb if no solution is known) - const FlatZincSpace* last = static_cast(mi.last()); + const FlatZincSpace* last = static_cast(sc.last()); assert(last == nullptr || last->on_restart_fv.size() == restart_data().on_restart_fv_sol); for (int i = 0; i < restart_data().on_restart_fv_sol; ++i) { FloatVar& outVar = on_restart_fv[base + restart_data().on_restart_fv_sol + i]; @@ -2314,30 +2313,31 @@ namespace Gecode { namespace FlatZinc { } #endif if (ret) { - return false; + // The on_restart constraints can restrict the spoke in any way + sc.coverage(SpokeCoverage::Partial); + return; } } - if ((mi.type() == MetaInfo::RESTART) && (mi.restart() != 0) && - (_lns > 0) && (mi.last()==nullptr) && (_lnsInitialSolution.size()>0)) { + if ((sc.engine() == MetaEngine::Restart) && (sc.episode() != 0) && + (_lns > 0) && (sc.last()==nullptr) && (_lnsInitialSolution.size()>0)) { for (unsigned int i=iv_lns.size(); i--;) { if (_random(99U) <= _lns) { rel(*this, iv_lns[i], IRT_EQ, _lnsInitialSolution[i]); } } - return false; - } else if ((mi.type() == MetaInfo::RESTART) && (mi.restart() != 0) && - (_lns > 0) && mi.last()) { + sc.coverage(SpokeCoverage::Partial); + } else if ((sc.engine() == MetaEngine::Restart) && (sc.episode() != 0) && + (_lns > 0) && (sc.last() != nullptr)) { const FlatZincSpace& last = - static_cast(*mi.last()); + static_cast(*sc.last()); for (unsigned int i=iv_lns.size(); i--;) { if (_random(99U) <= _lns) { rel(*this, iv_lns[i], IRT_EQ, last.iv_lns[i]); } } - return false; + sc.coverage(SpokeCoverage::Partial); } - return true; } Space* diff --git a/gecode/kernel/core.cpp b/gecode/kernel/core.cpp index e5407336c0..728aa83c37 100644 --- a/gecode/kernel/core.cpp +++ b/gecode/kernel/core.cpp @@ -901,28 +901,24 @@ namespace Gecode { throw SpaceNoComparison("Space::compare"); } - bool - Space::hub(const MetaInfo& mi) { - switch (mi.type()) { - case MetaInfo::RESTART: - if (mi.last() != nullptr) - constrain(*mi.last()); - mi.nogoods().post(*this); - // Perform a restart even if a solution has been found - return true; - case MetaInfo::PORTFOLIO: + void + Space::hub(HubContext& hc) { + switch (hc.engine()) { + case MetaEngine::Restart: + if (hc.last() != nullptr) + constrain(*hc.last()); + hc.nogoods().post(*this); + break; + case MetaEngine::Portfolio: // Kill all branchers BrancherGroup::all.kill(*this); - return true; + break; default: GECODE_NEVER; - return true; } } - bool - Space::spoke(const MetaInfo&) { - return true; - } + void + Space::spoke(SpokeContext&) {} void* diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 0e3c0cfcfb..8e76dee801 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -1651,97 +1651,243 @@ namespace Gecode { static NoGoods eng; }; + namespace Search { + class Statistics; + class MetaContextAccess; + } + /** - * \brief Information passed by meta search engines + * \defgroup TaskModelScriptMeta Meta search hooks + * + * A meta search engine keeps a \e hub space and searches clones of it, + * the \e spokes, with an inner engine. Restart-based search (RBS) runs + * one spoke after the other, each search of a spoke being an + * \e episode. Portfolio-based search (PBS) runs one spoke for each of + * its assets. + * + * The engines call Space::hub() on the hub and Space::spoke() on each + * spoke. A HubContext or SpokeContext tells the hook why it is called, + * and the hook answers through it: hub() with a MetaDecision, spoke() + * with a SpokeCoverage. * + * \ingroup TaskModelScript */ - class GECODE_VTABLE_EXPORT MetaInfo { - public: - /// Which type of information is provided - enum Type { - /// Information is provided by a restart-based engine - RESTART, - /// Information is provided by a portfolio-based engine - PORTFOLIO - }; - /// Reason for restarting - enum RestartReason { - /// No reason - used for PORTFOLIO - RR_NO, - /// Restarting after initialisation - RR_INIT, - /// Restarting after a solution is found - RR_SOL, - /// Restarting after exhausting search space - RR_CMPL, - /// Restarting after reaching restart limit - RR_LIM - }; + //@{ + + /// Meta search engine that calls a hook + enum class MetaEngine : unsigned char { + Restart, ///< Restart-based search (RBS) + Portfolio, ///< Portfolio-based search (PBS) + }; + + /** + * \brief Why a meta search engine calls a hook + * + * In Space::hub(), the event that ended the episode, or \c Start before + * the first one. In Space::spoke(), the event that ended the previous + * episode, or \c Start for the first episode and for the assets of a + * portfolio. + */ + enum class MetaEvent : unsigned char { + Start, ///< Search starts: no episode has run yet + Solution, ///< The episode found a solution + /** + * The episode exhausted its spoke. This is a proof only for a spoke + * of SpokeCoverage::Full, and then the engine has already ended: a + * hook only sees this event after a spoke of SpokeCoverage::Partial. + */ + Exhausted, + /** + * The inner engine ended without a proof (such as LDS). For a spoke + * of SpokeCoverage::Full, the engine has then already ended: a hook + * only sees this event after a spoke of SpokeCoverage::Partial. + */ + Incomplete, + Limit, ///< The episode reached the cutoff + }; + + /** + * \brief What a meta search engine does after Space::hub() returns + * + * The default is \c Restart. RBS honours \c Continue only after + * MetaEvent::Solution and restarts after any other event. PBS calls + * hub() only with MetaEvent::Start and ignores the decision. + */ + enum class MetaDecision : unsigned char { + /// Search a new spoke + Restart, + /// Continue the current episode: search the same spoke for the next solution + Continue, + }; + + /** + * \brief How much of the hub's search space a spoke covers + * + * Space::spoke() declares the coverage of its spoke. It decides whether + * exhausting the spoke proves that the hub has no further solution, and + * whether the no-goods recorded while searching the spoke hold in the + * hub. + * + * The engine trusts the declaration: a spoke that declares more coverage + * than it has, such as a spoke that removes solutions but declares + * \c Full, gives undefined results. + */ + enum class SpokeCoverage : unsigned char { + /** + * The spoke adds only branching and constraints that the hub + * implies: exhaustion is a proof + */ + Full, + /** + * The spoke explores part of the hub's search space, such as a large + * neighbourhood search fragment: exhaustion is no proof + */ + Partial, + }; + + /** + * \brief Information that a meta search engine passes to a hook + * + * Meta search engines create the contexts with + * Search::MetaContextAccess, models only read them. All references and + * pointers are valid only while the hook runs. + */ + class MetaContext { protected: - /// Type of information - const Type t; - /// \name Restart-based information - //@{ - /// Number of restarts - const unsigned long int r; - /// Reason for restarting - const RestartReason rr; - /// Number of solutions since last restart - const unsigned long long int s; - /// Number of failures since last restart - const unsigned long long int f; - /// Last solution found - const Space* l; - /// No-goods from restart - const NoGoods& ng; - //@} - /// \name Portfolio-based information - //@{ - /// Number of asset in portfolio - const unsigned int a; - //@} + /// The engine calling the hook + MetaEngine _engine; + /// Why the hook is called + MetaEvent _event; + /// The episode + unsigned long int _episode; + /// The asset + unsigned int _asset; + /// The number of assets + unsigned int _assets; + /// The most recent solution (possibly nullptr) + const Space* _last; + /// The statistics of the finished episode + const Search::Statistics& _statistics; + /// The no-goods of the finished episode + const NoGoods& _nogoods; + /// Initialize, the arguments correspond to the access functions + MetaContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, const Search::Statistics& statistics, + const NoGoods& nogoods); public: - /// \name Constructors depending on type of engine - //@{ - /// Constructor for restart-based engine - MetaInfo(unsigned long int r, - RestartReason rr, - unsigned long long int s, - unsigned long long int f, - const Space* l, - NoGoods& ng); - /// Constructor for portfolio-based engine - MetaInfo(unsigned int a); - //@} - /// Return type of information - Type type(void) const; - /// \name Restart-based information - //@{ - /// Return number of restarts - unsigned long int restart(void) const; - /// Return reason for restarting - RestartReason reason(void) const; - /// Return number of solutions since last restart - unsigned long long int solution(void) const; - /// Return number of failures since last restart - unsigned long long int fail(void) const; - /// Return last solution found (possibly nullptr) + /// Contexts are not copied + MetaContext(const MetaContext&) = delete; + /// Contexts are not assigned + MetaContext& operator =(const MetaContext&) = delete; + /// Return the engine calling the hook + MetaEngine engine(void) const; + /// Return why the hook is called + MetaEvent event(void) const; + /** + * \brief Return the episode, counting from zero + * + * Each new spoke of RBS starts a new episode, whatever ended the + * previous one. In hub(), this is the episode that ended (zero for + * \c Start); in spoke(), the episode that starts. PBS always passes + * zero. + */ + unsigned long int episode(void) const; + /// Return the asset of a portfolio, counting from zero (zero for RBS) + unsigned int asset(void) const; + /// Return the number of assets of a portfolio (one for RBS) + unsigned int assets(void) const; + /** + * \brief Return the most recent solution, or nullptr if none + * + * The engine owns the solution, and the pointer is valid only while + * the hook runs: clone the solution to keep it. + */ const Space* last(void) const; /** - * \brief Return no-goods recorded from restart + * \brief Return the statistics of the finished episode + * + * Empty for \c Start. Use the statistics of the engine for totals. + */ + const Search::Statistics& statistics(void) const; + /** + * \brief Return the no-goods of the finished episode * - * The no-goods are empty if the search on the spoke space was - * incomplete, as they only hold in the spoke's search space. + * The no-goods are empty if the spoke of the episode has + * SpokeCoverage::Partial, as they only hold in the spoke's search + * space. */ const NoGoods& nogoods(void) const; - //@} - /// \name Portfolio-based information - //@{ - /// Return number of asset in portfolio - unsigned int asset(void) const; - //@} }; + /// Context passed to Space::hub() + class HubContext : public MetaContext { + friend class Search::MetaContextAccess; + protected: + /// The decision + MetaDecision _decision; + private: + /// Initialize with decision MetaDecision::Restart + HubContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, const Search::Statistics& statistics, + const NoGoods& nogoods); + public: + /// Return the decision + MetaDecision decision(void) const; + /// Set the decision to \a d, the last one set counts + void decision(MetaDecision d); + }; + + /// Context passed to Space::spoke() + class SpokeContext : public MetaContext { + friend class Search::MetaContextAccess; + protected: + /// The coverage + SpokeCoverage _coverage; + private: + /// Initialize with coverage SpokeCoverage::Full + SpokeContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, const Search::Statistics& statistics, + const NoGoods& nogoods); + public: + /// Return the coverage + SpokeCoverage coverage(void) const; + /// Set the coverage to \a c, the last one set counts + void coverage(SpokeCoverage c); + }; + + namespace Search { + /** + * \brief Creation of the contexts of meta search hooks + * + * For meta search engines, which create the contexts that they pass + * to Space::hub() and Space::spoke(). The arguments correspond to the + * access functions of MetaContext. + */ + class MetaContextAccess { + public: + /// Return a context for Space::hub() with decision MetaDecision::Restart + static HubContext hub(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, const Statistics& statistics, + const NoGoods& nogoods); + /// Return a context for Space::spoke() with coverage SpokeCoverage::Full + static SpokeContext spoke(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, const Statistics& statistics, + const NoGoods& nogoods); + }; + } + + //@} + /** * \brief %Space status * \ingroup TaskSearch @@ -2192,55 +2338,54 @@ namespace Gecode { GECODE_KERNEL_EXPORT virtual SpaceComparison compare(const Space& other) const; /** - * \brief Hub configuration function for meta search engines - * - * \li Restart-based search (RBS) calls this function on its hub - * after each solution and before each restart. \a mi - * describes the restart. After a solution, returning true - * restarts search from a new spoke, and returning false - * continues the current search without calling spoke(). At a - * restart caused by the cutoff or by an incomplete spoke being - * exhausted, the result is ignored and search restarts. - * Whatever the result, if the hub fails after the call, RBS - * ends. - * - * The default function constrains the hub with the last - * solution, if any, posts the no-goods from \a mi, and - * returns true. - * - * \li Portfolio-based search (PBS) calls this function once on - * its hub before creating the assets. The result is ignored. - * - * The default function removes all branchers, so the spoke() - * function must post the branching for each asset. + * \brief Hub hook for meta search engines + * + * Restart-based search (RBS) calls hub() on its hub whenever an + * episode ends with a solution or at the cutoff, and when an episode + * that searches a spoke of SpokeCoverage::Partial is exhausted or + * ends without a proof (see MetaEvent). Any other episode that ends + * this way ends RBS with Search::EndReason::Exhausted or + * Search::EndReason::Incomplete instead. + * Portfolio-based search (PBS) calls hub() once, with + * MetaEvent::Start, before it creates the assets. + * + * The hook may post constraints in the hub and sets what the engine + * does next with \a hc.decision() (see MetaDecision). If the hub + * fails, RBS ends with Search::EndReason::Exhausted whatever + * the decision: failing the hub is how a hook declares that no + * further solution exists. + * + * The default hook constrains the hub with \a hc.last(), if any, and + * posts \a hc.nogoods() for RBS. For PBS, it removes all branchers, + * so spoke() must post the branching of each asset. * * \ingroup TaskModelScript */ GECODE_KERNEL_EXPORT - virtual bool hub(const MetaInfo& mi); + virtual void hub(HubContext& hc); /** - * \brief Spoke configuration function for meta search engines + * \brief Spoke hook for meta search engines * - * \li RBS calls this function on each spoke, a clone of the hub, - * before searching it: once when search starts and once at - * each restart. \a mi describes the restart. Returning true - * declares the search of the spoke complete: when it is - * exhausted, RBS finishes. Returning false declares it - * incomplete: when it is exhausted, RBS restarts. The no-goods - * recorded by an incomplete search only hold in the spoke's - * search space, so RBS does not pass them to hub(). This also - * holds for the first search when search starts. + * RBS calls spoke() on each new spoke, a clone of the hub, before + * searching it: for the first episode with MetaEvent::Start, and + * for each later episode with the event that ended the previous + * one. PBS calls spoke() once on the spoke of each asset, the hub + * or a clone of it, with MetaEvent::Start and the asset number. * - * \li PBS calls this function once on the spoke of each asset, - * the hub or a clone of it, and passes the asset number, - * starting from zero. The result is ignored. + * The hook may post constraints and branching in the spoke and + * declares with \a sc.coverage() how much of the hub's search space + * the spoke covers (see SpokeCoverage, the default is Full). Large + * neighbourhood search, for example, fixes part of \a sc.last() and + * declares SpokeCoverage::Partial. The no-goods recorded while + * searching a spoke of SpokeCoverage::Partial only hold in its + * search space, so RBS does not pass them to hub(). * - * The default function does nothing and returns true. + * The default hook does nothing. * * \ingroup TaskModelScript */ GECODE_KERNEL_EXPORT - virtual bool spoke(const MetaInfo& mi); + virtual void spoke(SpokeContext& sc); /* * Member functions for search engines @@ -3244,58 +3389,106 @@ namespace Gecode { /* - * Information from meta search engines + * Contexts of meta search hooks */ forceinline - MetaInfo::MetaInfo(unsigned long int r0, - RestartReason rr0, - unsigned long long int s0, - unsigned long long int f0, - const Space* l0, - NoGoods& ng0) - : t(RESTART), r(r0), rr(rr0), s(s0), f(f0), l(l0), ng(ng0), a(0) {} - - forceinline - MetaInfo::MetaInfo(unsigned int a0) - : t(PORTFOLIO), r(0), rr(RR_NO), s(0), f(0), l(nullptr), ng(NoGoods::eng), a(a0) {} - - forceinline MetaInfo::Type - MetaInfo::type(void) const { - return t; + MetaContext::MetaContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, + const Search::Statistics& statistics, + const NoGoods& nogoods) + : _engine(engine), _event(event), _episode(episode), + _asset(asset), _assets(assets), _last(last), + _statistics(statistics), _nogoods(nogoods) {} + forceinline MetaEngine + MetaContext::engine(void) const { + return _engine; + } + forceinline MetaEvent + MetaContext::event(void) const { + return _event; } forceinline unsigned long int - MetaInfo::restart(void) const { - assert(type() == RESTART); - return r; - } - forceinline MetaInfo::RestartReason - MetaInfo::reason(void) const { - return rr; + MetaContext::episode(void) const { + return _episode; } - forceinline unsigned long long int - MetaInfo::solution(void) const { - assert(type() == RESTART); - return s; + forceinline unsigned int + MetaContext::asset(void) const { + return _asset; } - forceinline unsigned long long int - MetaInfo::fail(void) const { - assert(type() == RESTART); - return f; + forceinline unsigned int + MetaContext::assets(void) const { + return _assets; } forceinline const Space* - MetaInfo::last(void) const { - assert(type() == RESTART); - return l; + MetaContext::last(void) const { + return _last; + } + forceinline const Search::Statistics& + MetaContext::statistics(void) const { + return _statistics; } forceinline const NoGoods& - MetaInfo::nogoods(void) const { - assert(type() == RESTART); - return ng; + MetaContext::nogoods(void) const { + return _nogoods; } - forceinline unsigned int - MetaInfo::asset(void) const { - assert(type() == PORTFOLIO); - return a; + + forceinline + HubContext::HubContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, + const Search::Statistics& statistics, + const NoGoods& nogoods) + : MetaContext(engine,event,episode,asset,assets,last,statistics,nogoods), + _decision(MetaDecision::Restart) {} + forceinline MetaDecision + HubContext::decision(void) const { + return _decision; + } + forceinline void + HubContext::decision(MetaDecision d) { + _decision = d; + } + + forceinline + SpokeContext::SpokeContext(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, + const Search::Statistics& statistics, + const NoGoods& nogoods) + : MetaContext(engine,event,episode,asset,assets,last,statistics,nogoods), + _coverage(SpokeCoverage::Full) {} + forceinline SpokeCoverage + SpokeContext::coverage(void) const { + return _coverage; + } + forceinline void + SpokeContext::coverage(SpokeCoverage c) { + _coverage = c; + } + + forceinline HubContext + Search::MetaContextAccess::hub(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, + const Statistics& statistics, + const NoGoods& nogoods) { + return HubContext(engine,event,episode,asset,assets,last,statistics, + nogoods); + } + forceinline SpokeContext + Search::MetaContextAccess::spoke(MetaEngine engine, MetaEvent event, + unsigned long int episode, + unsigned int asset, unsigned int assets, + const Space* last, + const Statistics& statistics, + const NoGoods& nogoods) { + return SpokeContext(engine,event,episode,asset,assets,last,statistics, + nogoods); } diff --git a/gecode/search.hh b/gecode/search.hh index 8fdbda55a9..b40565fed7 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1516,10 +1516,10 @@ namespace Gecode { * The engine uses the Cutoff sequence supplied in the options \a o to * periodically restart the search of engine \a E. * - * The class \a T can implement member functions - * \code virtual bool hub(const MetaInfo& mi) \endcode + * The class \a T can override the member functions + * \code virtual void hub(HubContext& hc) \endcode * and - * \code virtual bool spoke(const MetaInfo& mi) \endcode + * \code virtual void spoke(SpokeContext& sc) \endcode * * The engine calls hub() on its hub after solutions and at restarts, * and spoke() on each spoke it clones from the hub. See Space::hub() @@ -1548,10 +1548,10 @@ namespace Gecode { * The engine uses the Cutoff sequence supplied in the options \a o to * periodically restart the search of engine \a E. * - * The class \a T can implement member functions - * \code virtual bool hub(const MetaInfo& mi) \endcode + * The class \a T can override the member functions + * \code virtual void hub(HubContext& hc) \endcode * and - * \code virtual bool spoke(const MetaInfo& mi) \endcode + * \code virtual void spoke(SpokeContext& sc) \endcode * * The engine calls hub() on its hub after solutions and at restarts, * and spoke() on each spoke it clones from the hub. See Space::hub() @@ -1634,14 +1634,14 @@ namespace Gecode { * limit, is dropped while the other assets continue. When every asset * has been dropped, end_reason() returns Search::EndReason::Incomplete. * - * The class \a T can implement member functions - * \code virtual bool hub(const MetaInfo& mi) \endcode + * The class \a T can override the member functions + * \code virtual void hub(HubContext& hc) \endcode * and - * \code virtual bool spoke(const MetaInfo& mi) \endcode + * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() once on its hub and then spoke() on the - * spoke of each asset. See Space::hub() and Space::spoke() for - * details. + * The engine calls hub() once on its hub with MetaEvent::Start and then + * spoke() on the spoke of each asset. See Space::hub() and + * Space::spoke() for details. * * \ingroup TaskModelSearch */ @@ -1690,14 +1690,14 @@ namespace Gecode { * An external worker control is supported only when \a o selects one * asset. PBS does not implement worker-allocation policy. * - * The class \a T can implement member functions - * \code virtual bool hub(const MetaInfo& mi) \endcode + * The class \a T can override the member functions + * \code virtual void hub(HubContext& hc) \endcode * and - * \code virtual bool spoke(const MetaInfo& mi) \endcode + * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() once on its hub and then spoke() on the - * spoke of each asset. See Space::hub() and Space::spoke() for - * details. + * The engine calls hub() once on its hub with MetaEvent::Start and then + * spoke() on the spoke of each asset. See Space::hub() and + * Space::spoke() for details. * * \ingroup TaskModelSearch */ diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index 34990d41a7..7b739b2b62 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -148,6 +148,26 @@ namespace Gecode { namespace Search { delete c; } + /// Run hub() with MetaEvent::Start on the hub \a hub of a portfolio of \a n assets + forceinline void + pbs_hub(Space& hub, unsigned int n) { + Statistics start; + HubContext hc = MetaContextAccess::hub(MetaEngine::Portfolio, + MetaEvent::Start,0UL,0U,n, + nullptr,start,NoGoods::eng); + hub.hub(hc); + } + + /// Run spoke() on the spoke \a s of asset \a i of \a n + forceinline void + pbs_spoke(Space& s, unsigned int i, unsigned int n) { + Statistics start; + SpokeContext sc = MetaContextAccess::spoke(MetaEngine::Portfolio, + MetaEvent::Start,0UL,i,n, + nullptr,start,NoGoods::eng); + s.spoke(sc); + } + /// A PBS engine builder template class E> class PbsBuilder : public Builder { @@ -242,7 +262,7 @@ namespace Gecode { namespace Search { hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; - (void) spoke->spoke(i); + pbs_spoke(*spoke,i,n_assets); std::unique_ptr c(pbs_cutoff >(cutoff)); if (c != nullptr) opt.cutoff = c.get(); @@ -290,7 +310,8 @@ namespace Gecode { namespace Search { hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; - (void) spoke->spoke(static_cast(i)); + pbs_spoke(*spoke,static_cast(i), + static_cast(n_assets)); assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); @@ -340,7 +361,7 @@ namespace Gecode { namespace Search { hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; - (void) spoke->spoke(static_cast(i)); + pbs_spoke(*spoke,i,n_assets); std::unique_ptr c(pbs_cutoff >(cutoff)); if (c != nullptr) opt.cutoff = c.get(); @@ -390,7 +411,8 @@ namespace Gecode { namespace Search { hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; - (void) spoke->spoke(static_cast(i)); + pbs_spoke(*spoke,static_cast(i), + static_cast(n_assets)); assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); @@ -443,12 +465,12 @@ namespace Gecode { opt.clone = false; // Always execute hub function - (void) hub->hub(0); + Search::pbs_hub(*hub,opt.assets); // No need to create a portfolio engine but must run spoke function if (o.assets == 1) { std::unique_ptr seed(hub); - (void) hub->spoke(0); + Search::pbs_spoke(*hub,0U,1U); // Retain the seed if a nested builder rejects its worker control. opt.clone = true; e = Search::build(seed.get(),opt); @@ -497,7 +519,7 @@ namespace Gecode { opt.clone = false; // Always execute hub function - (void) hub->hub(0); + Search::pbs_hub(*hub,static_cast(sebs.size())); #ifdef GECODE_HAS_THREADS if (opt.threads > 1.0) diff --git a/gecode/search/rbs.cpp b/gecode/search/rbs.cpp index 1b78157317..f54e6ff54d 100644 --- a/gecode/search/rbs.cpp +++ b/gecode/search/rbs.cpp @@ -43,15 +43,15 @@ namespace Gecode { namespace Search { namespace Seq { Engine* rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, bool best) { - return rbsengine(hub,stop,engine,stat,opt,best,true); + return rbsengine(hub,stop,engine,stat,opt,best,SpokeCoverage::Full); } Engine* rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, bool best, - bool complete) { + SpokeCoverage coverage) { return new RBS(hub,static_cast(stop), engine, - stat,opt,best,complete); + stat,opt,best,coverage); } diff --git a/gecode/search/rbs.hpp b/gecode/search/rbs.hpp index 89ffef358a..f9b4f75068 100644 --- a/gecode/search/rbs.hpp +++ b/gecode/search/rbs.hpp @@ -43,7 +43,7 @@ namespace Gecode { namespace Search { namespace Seq { GECODE_SEARCH_EXPORT Stop* rbsstop(Stop* so); - /// Create restart engine whose first spoke search yields valid no-goods + /// Create restart engine whose first spoke has SpokeCoverage::Full GECODE_SEARCH_EXPORT Engine* rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, @@ -52,14 +52,13 @@ namespace Gecode { namespace Search { namespace Seq { /** * \brief Create restart engine * - * The value \a complete is the result of the spoke configuration of the - * space explored by the first \a engine. It only determines whether - * the no-goods of that search hold in the hub. + * The value \a coverage is the coverage that the spoke hook declared for + * the space explored by the first \a engine. */ GECODE_SEARCH_EXPORT Engine* rbsengine(Space* hub, Stop* stop, Engine* engine, const Search::Statistics& stat, const Options& opt, - bool best, bool complete); + bool best, SpokeCoverage coverage); }}} @@ -114,12 +113,15 @@ namespace Gecode { } else { std::unique_ptr hub(m_opt.clone ? s->clone() : s); std::unique_ptr spoke(hub->clone()); - MetaInfo mi(0,MetaInfo::RR_INIT,0,0,nullptr,NoGoods::eng); - bool complete = spoke->spoke(mi); + Search::Statistics start; + SpokeContext sc = Search::MetaContextAccess::spoke( + MetaEngine::Restart,MetaEvent::Start,0UL,0U,1U,nullptr,start, + NoGoods::eng); + spoke->spoke(sc); std::unique_ptr leaf( Search::build(spoke.get(),e_opt)); e = Search::Seq::rbsengine(hub.get(),stop.get(),leaf.get(), - stat,m_opt,E::best,complete); + stat,m_opt,E::best,sc.coverage()); hub.release(); stop.release(); leaf.release(); diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index 25696ea86a..ab80f7ef55 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -66,9 +66,9 @@ namespace Gecode { namespace Search { namespace Seq { NoGoods& RBS::hub_nogoods(void) { - // The no-goods of an incomplete spoke search only hold in its restricted - // search space, not in the hub. - if (!nogoods_valid) + // The no-goods of a partial spoke only hold in its restricted search + // space, not in the hub. + if (coverage == SpokeCoverage::Partial) return NoGoods::eng; NoGoods& ng = e->nogoods(); // Reset number of no-goods found @@ -76,6 +76,48 @@ namespace Gecode { namespace Search { namespace Seq { return ng; } + bool + RBS::hub_event(MetaEvent ev) { + Search::Statistics episode_stat = e->statistics(); + NoGoods& ng = hub_nogoods(); + HubContext hc = MetaContextAccess::hub(MetaEngine::Restart,ev,episode, + 0U,1U,last,episode_stat,ng); + hub->hub(hc); + stop->nogood(ng.ng()); + // Only an episode that found a solution can continue + bool cont = (ev == MetaEvent::Solution) && + (hc.decision() == MetaDecision::Continue); + // Any other episode ends with a restart that takes the next cutoff + if (ev != MetaEvent::Solution) + stop->limit(e->statistics(),++(*co)); + if (stop->status(hub) == SS_FAILED) { + // A failed hub proves that no further solution exists + if (ev == MetaEvent::Solution) + stop->update(e->statistics()); + delete hub; + hub = nullptr; + e->reset(nullptr); + end = EndReason::Exhausted; + return false; + } + if (cont) + return true; + if (ev == MetaEvent::Solution) { + // A restart after a solution keeps the cutoff + stop->update(e->statistics()); + stop->restart(); + } + Space* spoke = hub; + hub = hub->clone(); + episode++; + SpokeContext sc = MetaContextAccess::spoke(MetaEngine::Restart,ev,episode, + 0U,1U,last,episode_stat,ng); + spoke->spoke(sc); + coverage = sc.coverage(); + e->reset(spoke); + return true; + } + Space* RBS::next(void) { // A failed hub proves that no further solution exists @@ -83,83 +125,66 @@ namespace Gecode { namespace Search { namespace Seq { end = EndReason::Exhausted; return nullptr; } - if (restart) { - restart = false; - sslr++; - NoGoods& ng = hub_nogoods(); - MetaInfo mi(stop->restarts(),MetaInfo::RR_SOL,sslr,e->statistics().fail,last,ng); - bool r = hub->hub(mi); - stop->nogood(ng.ng()); - if (stop->status(hub) == SS_FAILED) { - stop->update(e->statistics()); - delete hub; - hub = nullptr; - e->reset(nullptr); - end = EndReason::Exhausted; + if (solution) { + solution = false; + if (!hub_event(MetaEvent::Solution)) return nullptr; - } else if (r) { - stop->update(e->statistics()); - Space* spoke = hub; - hub = hub->clone(); - complete = spoke->spoke(mi); - nogoods_valid = complete; - e->reset(spoke); - sslr = 0; - stop->restart(); - } } while (true) { Space* n = e->next(); if (n != nullptr) { // The engine found a solution - restart = true; + solution = true; delete last; last = n->clone(); end = EndReason::NotEnded; return n; } - EndReason inner = e->end_reason(); - bool limit = inner == EndReason::Limit; - if ((!complete && !limit) || (limit && stop->enginestopped())) { - // The engine must perform a true restart - // The number of the restart has been incremented in the stop object - if (!complete && !limit) { - /* - * The engine might not have checked its stop object, for example - * when the spoke failed at the root or a parallel engine had no - * work. Without this check, the restarts might never stop. - */ - if (stop->meta_stop(e->statistics(),m_opt)) { - end = EndReason::Limit; - return nullptr; - } - stop->restart(); + MetaEvent ev; + switch (e->end_reason()) { + case EndReason::Limit: + if (!stop->enginestopped()) { + // A stop from above + end = EndReason::Limit; + return nullptr; } - sslr = 0; - NoGoods& ng = hub_nogoods(); - MetaInfo mi(stop->restarts(),limit ? MetaInfo::RR_LIM : MetaInfo::RR_CMPL,sslr,e->statistics().fail,last,ng); - (void) hub->hub(mi); - stop->nogood(ng.ng()); - unsigned long long int nl = ++(*co); - stop->limit(e->statistics(),nl); - if (stop->status(hub) == SS_FAILED) { - // The statistics of the engine have been added by limit() - delete hub; - hub = nullptr; - e->reset(nullptr); + // The stop object has counted the restart + ev = MetaEvent::Limit; + break; + case EndReason::Exhausted: + if (coverage != SpokeCoverage::Partial) { + // The spoke covers the hub, so this is a proof end = EndReason::Exhausted; return nullptr; } - Space* spoke = hub; - hub = hub->clone(); - complete = spoke->spoke(mi); - nogoods_valid = complete; - e->reset(spoke); - } else { - // A stop from above, or a complete spoke search has ended - end = inner; + ev = MetaEvent::Exhausted; + break; + case EndReason::Incomplete: + if (coverage != SpokeCoverage::Partial) { + // A new spoke would repeat the same incomplete search + end = EndReason::Incomplete; + return nullptr; + } + ev = MetaEvent::Incomplete; + break; + default: + GECODE_NEVER; return nullptr; } + if (ev != MetaEvent::Limit) { + /* + * The engine might not have checked its stop object, for example + * when the spoke failed at the root or a parallel engine had no + * work. Without this check, the restarts might never stop. + */ + if (stop->meta_stop(e->statistics(),m_opt)) { + end = EndReason::Limit; + return nullptr; + } + stop->restart(); + } + if (!hub_event(ev)) + return nullptr; } GECODE_NEVER; return nullptr; diff --git a/gecode/search/seq/rbs.hh b/gecode/search/seq/rbs.hh index 4d930f2065..4daa27e18a 100755 --- a/gecode/search/seq/rbs.hh +++ b/gecode/search/seq/rbs.hh @@ -66,15 +66,13 @@ namespace Gecode { namespace Search { namespace Seq { virtual bool stop(const Statistics& s, const Options& o); /// Return true if the stop object for the meta engine says so bool meta_stop(const Statistics& s, const Options& o); - /// Return current restart count - unsigned long int restarts(void) const; /// Increment current restart count void restart(void); /// Add no-goods to meta statistics void nogood(unsigned long int n); /// Test hub status with meta statistics SpaceStatus status(Space* s); - /// Set current limit for the engine to \a l fails + /// Add statistics \a s and set the limit for the engine to \a l fails void limit(const Statistics& s, unsigned long long int l); /// Update statistics void update(const Search::Statistics& s); @@ -99,31 +97,30 @@ namespace Gecode { namespace Search { namespace Seq { RestartStop* stop; /// The options for the stop object of the meta engine Options m_opt; - /// How many solutions since the last restart - unsigned long int sslr; - /// Whether search for the next solution will be complete - bool complete; - /// Whether the no-goods of the current spoke search hold in the hub - bool nogoods_valid; - /// Whether a restart must be performed when next is called - bool restart; + /// The current episode + unsigned long int episode; + /// The coverage of the spoke of the current episode + SpokeCoverage coverage; + /// Whether the last call to next() returned a solution that hub() has not seen + bool solution; /// Whether the engine performs best solution search bool best; /// Why the last call to next() returned no solution EndReason end; /// Return the no-goods of the last spoke search, valid in the hub NoGoods& hub_nogoods(void); + /// Call hub() for event \a ev and act on its decision, return whether search continues + bool hub_event(MetaEvent ev); public: /** * \brief Constructor * - * The value \a complete is the result of the spoke configuration of the - * space explored by the first engine \a e0, and is used as for the - * searches after later restarts. + * The value \a coverage is the coverage that the spoke hook declared + * for the space explored by the first engine \a e0. */ RBS(Space* s, RestartStop* stop0, Engine* e0, const Search::Statistics& stat, const Options& o, bool best, - bool complete); + SpokeCoverage coverage); /// Return next solution (nullptr, if none exists or search has been stopped) virtual Space* next(void); /// Return statistics diff --git a/gecode/search/seq/rbs.hpp b/gecode/search/seq/rbs.hpp index ba428fd7ba..854d26e9b4 100755 --- a/gecode/search/seq/rbs.hpp +++ b/gecode/search/seq/rbs.hpp @@ -42,12 +42,6 @@ namespace Gecode { namespace Search { namespace Seq { RestartStop::RestartStop(Stop* s) : l(0U), m_stop(s), e_stopped(false) {} - forceinline unsigned long int - RestartStop::restarts(void) const { - Support::Lock lock(m); - return m_stat.restart; - } - forceinline void RestartStop::restart(void) { Support::Lock lock(m); @@ -96,10 +90,10 @@ namespace Gecode { namespace Search { namespace Seq { forceinline RBS::RBS(Space* s, RestartStop* stop0, Engine* e0, const Search::Statistics& stat, const Options& opt, - bool best0, bool complete0) + bool best0, SpokeCoverage coverage0) : e(e0), hub(s), last(nullptr), co(opt.cutoff), stop(stop0), - m_opt(opt.expand()), sslr(0), - complete(complete0), nogoods_valid(complete0), restart(false), + m_opt(opt.expand()), episode(0UL), coverage(coverage0), + solution(false), best(best0), end(EndReason::NotEnded) { stop->limit(stat,(*co)()); } diff --git a/test/search.cpp b/test/search.cpp index a87186b52b..735591d9c4 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -152,7 +152,7 @@ namespace Test { : Space(s), graph(s.graph), maximize(s.maximize), vertex(s.vertex), ceiling(s.ceiling) {} Space* copy(void) override { return new TreeSpace(*this); } - bool hub(const MetaInfo&) override { return true; } + void hub(HubContext&) override {} const Node& node(void) const { return (*graph)[vertex]; } void constrain(const Space& s) override { ceiling = static_cast(s).node().cost; @@ -405,14 +405,13 @@ namespace Test { virtual int solutions(void) const = 0; /// Verify that this is best solution virtual bool best(void) const = 0; - /// Hub configuration function that does not restart - virtual bool hub(const MetaInfo& mi) { - if (mi.type() == MetaInfo::RESTART) { - if (mi.last() != nullptr) - constrain(*mi.last()); - return false; - } else { - return false; + /// Hub hook that does not restart after a solution and keeps the branchers of a portfolio + virtual void hub(HubContext& hc) { + if (hc.engine() == MetaEngine::Restart) { + if (hc.last() != nullptr) + constrain(*hc.last()); + if (hc.event() == MetaEvent::Solution) + hc.decision(MetaDecision::Continue); } } }; @@ -651,43 +650,40 @@ namespace Test { return "Sol"; } /// Rule out that solution is found more than once during restarts - virtual bool hub(const MetaInfo& mi) { - switch (mi.type()) { - case MetaInfo::RESTART: - // With an objective, restart from a bound improving on the last solution - if (htc != HTC_NONE) - return Space::hub(mi); - if (mi.last() != nullptr) { - const HasSolutions* s - = static_cast(mi.last()); - BoolVarArgs b; - for (int i=0; ix[i]); - rel(*this, BOT_AND, b, 0); - } - break; - case MetaInfo::PORTFOLIO: - // Do not kill the brancher! - break; - default: - break; + virtual void hub(HubContext& hc) { + // For portfolio search, keep the branchers + if (hc.engine() != MetaEngine::Restart) + return; + // With an objective, restart from a bound improving on the last solution + if (htc != HTC_NONE) { + Space::hub(hc); + return; } - return false; + if (hc.last() != nullptr) { + const HasSolutions* s + = static_cast(hc.last()); + BoolVarArgs b; + for (int i=0; ix[i]); + rel(*this, BOT_AND, b, 0); + } + if (hc.event() == MetaEvent::Solution) + hc.decision(MetaDecision::Continue); } }; - /// Return a bit for restart reason \a r + /// Return a bit for meta event \a e static unsigned int - reason_bit(MetaInfo::RestartReason r) { - return 1U << static_cast(r); + event_bit(MetaEvent e) { + return 1U << static_cast(e); } /// Observations shared by meta-search dispatch test spaces struct MetaDispatchState { std::atomic hub_calls{0}; std::atomic spoke_calls{0}; - std::atomic hub_reasons{0}; - std::atomic spoke_reasons{0}; + std::atomic hub_events{0}; + std::atomic spoke_events{0}; std::atomic assets{0}; std::atomic live_spaces{0}; std::atomic copies{0}; @@ -698,8 +694,10 @@ namespace Test { std::atomic constrain_hub_asset_mask{0}; std::atomic constrain_spoke_asset_mask{0}; std::atomic nogood_handoffs{0}; - bool restart_after_solution = true; - bool solution_spoke_complete = true; + /// Decision of hub() after a solution + MetaDecision solution_decision = MetaDecision::Restart; + /// Coverage that spoke() declares after a solution + SpokeCoverage solution_spoke_coverage = SpokeCoverage::Full; bool fail_solution_spoke = false; bool nogood_model = false; /// Whether a PBS spoke() posts the branching for its asset @@ -727,43 +725,45 @@ namespace Test { int portfolio_asset; /// Record and implement a Hub callback - bool - observe_hub(const MetaInfo& mi) { + void + observe_hub(HubContext& hc) { state->hub_calls.fetch_add(1, std::memory_order_relaxed); - if (mi.type() == MetaInfo::PORTFOLIO) - // PBS must ignore the callback result. - return false; + // Keep the branchers of a portfolio hub + if (hc.engine() == MetaEngine::Portfolio) + return; restart_role = RestartRole::Hub; - state->hub_reasons.fetch_or(reason_bit(mi.reason()), std::memory_order_relaxed); - bool default_result = Space::hub(mi); - if ((mi.type() == MetaInfo::RESTART) && (mi.nogoods().ng() > 0)) + state->hub_events.fetch_or(event_bit(hc.event()), std::memory_order_relaxed); + Space::hub(hc); + if (hc.nogoods().ng() > 0) state->nogood_handoffs.fetch_add(1, std::memory_order_relaxed); - return (mi.reason() == MetaInfo::RR_SOL) ? state->restart_after_solution : default_result; + if (hc.event() == MetaEvent::Solution) + hc.decision(state->solution_decision); } /// Record and implement a Spoke callback - bool - observe_spoke(const MetaInfo& mi) { + void + observe_spoke(SpokeContext& sc) { state->spoke_calls.fetch_add(1, std::memory_order_relaxed); - if (mi.type() == MetaInfo::PORTFOLIO) { - portfolio_asset = static_cast(mi.asset()); - state->assets.fetch_or(1U << mi.asset(), std::memory_order_relaxed); + if (sc.engine() == MetaEngine::Portfolio) { + portfolio_asset = static_cast(sc.asset()); + state->assets.fetch_or(1U << sc.asset(), std::memory_order_relaxed); // The default hub() removes the model's branching. A hub() // override keeps it, and then this branching is redundant. if (state->spoke_branching) Gecode::branch(*this, x, INT_VAL_MIN()); - // PBS must ignore the callback result. - return false; + return; } - state->spoke_reasons.fetch_or(reason_bit(mi.reason()), std::memory_order_relaxed); + state->spoke_events.fetch_or(event_bit(sc.event()), std::memory_order_relaxed); restart_role = RestartRole::Spoke; - if ((mi.reason() == MetaInfo::RR_INIT) && state->limit_first_spoke) { + if ((sc.event() == MetaEvent::Start) && state->limit_first_spoke) { // Four distinct values from three fail only during search. distinct(*this, y, IPL_VAL); Gecode::branch(*this, y, INT_VAR_NONE(), INT_VAL_MIN()); } - if ((mi.reason() == MetaInfo::RR_SOL) && state->fail_solution_spoke) - fail(); - return (mi.reason() == MetaInfo::RR_SOL) ? state->solution_spoke_complete : true; + if (sc.event() == MetaEvent::Solution) { + if (state->fail_solution_spoke) + fail(); + sc.coverage(state->solution_spoke_coverage); + } } public: @@ -846,9 +846,9 @@ namespace Test { return new HubDispatchSpace(*this); } /// Observe Hub dispatch - bool - hub(const MetaInfo& mi) override { - return observe_hub(mi); + void + hub(HubContext& hc) override { + observe_hub(hc); } }; @@ -865,9 +865,9 @@ namespace Test { return new SpokeDispatchSpace(*this); } /// Observe Spoke dispatch - bool - spoke(const MetaInfo& mi) override { - return observe_spoke(mi); + void + spoke(SpokeContext& sc) override { + observe_spoke(sc); } }; @@ -884,14 +884,14 @@ namespace Test { return new HubSpokeDispatchSpace(*this); } /// Observe Hub dispatch - bool - hub(const MetaInfo& mi) override { - return observe_hub(mi); + void + hub(HubContext& hc) override { + observe_hub(hc); } /// Observe Spoke dispatch - bool - spoke(const MetaInfo& mi) override { - return observe_spoke(mi); + void + spoke(SpokeContext& sc) override { + observe_spoke(sc); } }; @@ -904,8 +904,8 @@ namespace Test { RbsSpokeOnly, RbsHubContinue, RbsHubRestart, - RbsSpokeComplete, - RbsSpokeIncomplete, + RbsSpokeFull, + RbsSpokePartial, RbsLimit, PbsHubOnly, PbsSpokeOnly, @@ -954,11 +954,12 @@ namespace Test { } /// Run one RBS dispatch scenario static bool - rbs(bool restart_after_solution, bool fail_solution_spoke, bool solution_spoke_complete) { + rbs(MetaDecision solution_decision, bool fail_solution_spoke, + SpokeCoverage solution_spoke_coverage) { MetaDispatchState state; - state.restart_after_solution = restart_after_solution; + state.solution_decision = solution_decision; state.fail_solution_spoke = fail_solution_spoke; - state.solution_spoke_complete = solution_spoke_complete; + state.solution_spoke_coverage = solution_spoke_coverage; HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(state); Gecode::Search::Options o; @@ -971,22 +972,27 @@ namespace Test { bool ok = first != nullptr; delete first; + const unsigned int start = event_bit(MetaEvent::Start); + const unsigned int solution = event_bit(MetaEvent::Solution); + const unsigned int exhausted = event_bit(MetaEvent::Exhausted); HubSpokeDispatchSpace* second = search.next(); if (!fail_solution_spoke) { + const bool restart = solution_decision == MetaDecision::Restart; ok = ok && (second != nullptr) && holds(state.hub_calls, 1U) && - holds(state.spoke_calls, restart_after_solution ? 2U : 1U) && - holds(state.hub_reasons, reason_bit(MetaInfo::RR_SOL)) && - holds(state.spoke_reasons, reason_bit(MetaInfo::RR_INIT) | - (restart_after_solution ? reason_bit(MetaInfo::RR_SOL) : 0U)); - } else if (solution_spoke_complete) { - ok = ok && (second == nullptr) && holds(state.hub_calls, 1U) && holds(state.spoke_calls, 2U) && - holds(state.hub_reasons, reason_bit(MetaInfo::RR_SOL)) && - holds(state.spoke_reasons, reason_bit(MetaInfo::RR_INIT) | reason_bit(MetaInfo::RR_SOL)); + holds(state.spoke_calls, restart ? 2U : 1U) && + holds(state.hub_events, solution) && + holds(state.spoke_events, start | (restart ? solution : 0U)); + } else if (solution_spoke_coverage == SpokeCoverage::Full) { + // Exhausting a spoke of full coverage is a proof + ok = ok && (second == nullptr) && + (search.end_reason() == EndReason::Exhausted) && + holds(state.hub_calls, 1U) && holds(state.spoke_calls, 2U) && + holds(state.hub_events, solution) && + holds(state.spoke_events, start | solution); } else { ok = ok && (second != nullptr) && holds(state.hub_calls, 2U) && holds(state.spoke_calls, 3U) && - holds(state.hub_reasons, reason_bit(MetaInfo::RR_SOL) | reason_bit(MetaInfo::RR_CMPL)) && - holds(state.spoke_reasons, reason_bit(MetaInfo::RR_INIT) | reason_bit(MetaInfo::RR_SOL) | - reason_bit(MetaInfo::RR_CMPL)); + holds(state.hub_events, solution | exhausted) && + holds(state.spoke_events, start | solution | exhausted); } delete second; return ok; @@ -1044,8 +1050,8 @@ namespace Test { HubSpokeDispatchSpace* solution = search.next(); bool ok = (solution != nullptr) && solution->assigned() && holds(state.hub_calls, 1U) && - holds(state.spoke_calls, 2U) && holds(state.hub_reasons, reason_bit(MetaInfo::RR_LIM)) && - holds(state.spoke_reasons, reason_bit(MetaInfo::RR_INIT) | reason_bit(MetaInfo::RR_LIM)); + holds(state.spoke_calls, 2U) && holds(state.hub_events, event_bit(MetaEvent::Limit)) && + holds(state.spoke_events, event_bit(MetaEvent::Start) | event_bit(MetaEvent::Limit)); delete solution; return ok; } @@ -1085,7 +1091,7 @@ namespace Test { meta_stop_ownership(void) { MetaDispatchState rbs_state; // Continue after a solution, so that the spoke engine prunes with it - rbs_state.restart_after_solution = false; + rbs_state.solution_decision = MetaDecision::Continue; bool ok = true; { Gecode::Search::NodeStop stop(0); @@ -1127,7 +1133,7 @@ namespace Test { bab_incumbent(void) { MetaDispatchState rbs_state; // Continue after a solution, so that the spoke engine prunes with it - rbs_state.restart_after_solution = false; + rbs_state.solution_decision = MetaDecision::Continue; bool ok = true; { HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(rbs_state); @@ -1175,7 +1181,7 @@ namespace Test { ok = ok && holds(pbs_state.live_spaces, 0U); MetaDispatchState nested_state; - nested_state.restart_after_solution = false; + nested_state.solution_decision = MetaDecision::Continue; { HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(nested_state); Gecode::Search::Options outer; @@ -1217,13 +1223,13 @@ namespace Test { case Scenario::RbsSpokeOnly: return rbs_dispatch(0, 2); case Scenario::RbsHubContinue: - return rbs(false, false, true); + return rbs(MetaDecision::Continue, false, SpokeCoverage::Full); case Scenario::RbsHubRestart: - return rbs(true, false, true); - case Scenario::RbsSpokeComplete: - return rbs(true, true, true); - case Scenario::RbsSpokeIncomplete: - return rbs(true, true, false); + return rbs(MetaDecision::Restart, false, SpokeCoverage::Full); + case Scenario::RbsSpokeFull: + return rbs(MetaDecision::Restart, true, SpokeCoverage::Full); + case Scenario::RbsSpokePartial: + return rbs(MetaDecision::Restart, true, SpokeCoverage::Partial); case Scenario::RbsLimit: return rbs_limit(); case Scenario::PbsHubOnly: @@ -1849,10 +1855,10 @@ namespace Test { } virtual Space* copy(void) { return new ParallelObjective(*this); } virtual IntVar cost(void) const { return x; } - virtual bool hub(const MetaInfo& mi) { - if (mi.type() == MetaInfo::PORTFOLIO) - return false; - return Space::hub(mi); + virtual void hub(HubContext& hc) { + // Keep the branchers for the assets of a portfolio + if (hc.engine() == MetaEngine::Restart) + Space::hub(hc); } }; @@ -1892,10 +1898,10 @@ namespace Test { throw ComparisonError(); return SpaceComparison::Incomparable; } - virtual bool hub(const MetaInfo& mi) { - if (mi.type() == MetaInfo::PORTFOLIO) - return false; - return Space::hub(mi); + virtual void hub(HubContext& hc) { + // Keep the branchers for the assets of a portfolio + if (hc.engine() == MetaEngine::Restart) + Space::hub(hc); } }; @@ -2873,14 +2879,13 @@ namespace Test { Gecode::IntVar cost(void) const override { return x[0]; } - bool spoke(const Gecode::MetaInfo& mi) override { - if ((mi.type() == Gecode::MetaInfo::RESTART) && - (mi.reason() == Gecode::MetaInfo::RR_INIT)) { + void spoke(Gecode::SpokeContext& sc) override { + if ((sc.engine() == Gecode::MetaEngine::Restart) && + (sc.event() == Gecode::MetaEvent::Start)) { Gecode::dom(*this,x[2],0,1); Gecode::dom(*this,x[3],0,1); - return false; + sc.coverage(Gecode::SpokeCoverage::Partial); } - return true; } }; @@ -2927,11 +2932,10 @@ namespace Test { Gecode::IntVar cost(void) const override { return x[0]; } - bool hub(const Gecode::MetaInfo& mi) override { + void hub(Gecode::HubContext& hc) override { // Keep the branchers for the assets of a portfolio - if (mi.type() == Gecode::MetaInfo::PORTFOLIO) - return true; - return Gecode::IntMinimizeSpace::hub(mi); + if (hc.engine() == Gecode::MetaEngine::Restart) + Gecode::IntMinimizeSpace::hub(hc); } }; @@ -2943,11 +2947,9 @@ namespace Test { Gecode::Space* copy(void) override { return new FailingHub(*this); } - bool hub(const Gecode::MetaInfo& mi) override { - if ((mi.type() == Gecode::MetaInfo::RESTART) && - (mi.reason() == Gecode::MetaInfo::RR_LIM)) + void hub(Gecode::HubContext& hc) override { + if (hc.event() == Gecode::MetaEvent::Limit) fail(); - return true; } }; @@ -2993,12 +2995,12 @@ namespace Test { Gecode::Space* copy(void) override { return new FailingSpoke(*this); } - bool spoke(const Gecode::MetaInfo& mi) override { - if ((mi.type() == Gecode::MetaInfo::RESTART) && (mi.restart() > 0)) { + void spoke(Gecode::SpokeContext& sc) override { + if ((sc.engine() == Gecode::MetaEngine::Restart) && + (sc.episode() > 0)) { fail(); - return false; + sc.coverage(Gecode::SpokeCoverage::Partial); } - return true; } }; @@ -3051,13 +3053,12 @@ namespace Test { Gecode::Space* copy(void) override { return new FailingFirstSpoke(*this); } - bool spoke(const Gecode::MetaInfo& mi) override { - if ((mi.type() == Gecode::MetaInfo::RESTART) && - (mi.reason() == Gecode::MetaInfo::RR_INIT)) { + void spoke(Gecode::SpokeContext& sc) override { + if ((sc.engine() == Gecode::MetaEngine::Restart) && + (sc.event() == Gecode::MetaEvent::Start)) { fail(); - return false; + sc.coverage(Gecode::SpokeCoverage::Partial); } - return true; } }; @@ -3631,10 +3632,10 @@ namespace Test { Gecode::Space* copy(void) override { return new FailingAsset(*this); } - bool spoke(const Gecode::MetaInfo& mi) override { - if ((mi.type() == Gecode::MetaInfo::PORTFOLIO) && (mi.asset() == 0U)) + void spoke(Gecode::SpokeContext& sc) override { + if ((sc.engine() == Gecode::MetaEngine::Portfolio) && + (sc.asset() == 0U)) fail(); - return true; } }; @@ -3810,8 +3811,8 @@ namespace Test { (void)new MetaDispatch("RBS::SpokeOnly", MetaDispatch::Scenario::RbsSpokeOnly); (void)new MetaDispatch("RBS::HubContinue", MetaDispatch::Scenario::RbsHubContinue); (void)new MetaDispatch("RBS::HubRestart", MetaDispatch::Scenario::RbsHubRestart); - (void)new MetaDispatch("RBS::SpokeComplete", MetaDispatch::Scenario::RbsSpokeComplete); - (void)new MetaDispatch("RBS::SpokeIncomplete", MetaDispatch::Scenario::RbsSpokeIncomplete); + (void)new MetaDispatch("RBS::SpokeFull", MetaDispatch::Scenario::RbsSpokeFull); + (void)new MetaDispatch("RBS::SpokePartial", MetaDispatch::Scenario::RbsSpokePartial); (void)new MetaDispatch("RBS::Limit", MetaDispatch::Scenario::RbsLimit); (void)new MetaDispatch("RBS::NoGoodsResetOwnership", MetaDispatch::Scenario::RbsNoGoodsResetOwnership); From b9a62fbe15789c770a71581e7bb43959aeb40e07 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 20:46:56 +0100 Subject: [PATCH 09/37] Honour spoke coverage for no-goods and in portfolio search SpokeCoverage::Reduced declares a spoke that prunes solutions but keeps one, or an optimal one, if any exists, such as a spoke with symmetry breaking or dominance constraints. Exhausting it is a proof, as for Full, but its no-goods do not hold in the hub. Restart-based search posts only the no-goods of a Full spoke in the hub, so the no-goods of a Reduced spoke stay in that spoke, as those of a Partial spoke already did. Portfolio search honours the coverage of every asset: an asset with a Partial spoke that is exhausted is dropped instead of ending the portfolio. This also holds for a portfolio of a single asset, which then runs inside a portfolio engine instead of as the bare asset engine. --- changelog.in | 3 +- docs/gecode-7-migration.md | 15 +++++-- gecode/kernel/core.hpp | 34 +++++++++------ gecode/search.hh | 15 ++++--- gecode/search/par/pbs.hh | 13 ++++-- gecode/search/par/pbs.hpp | 18 +++++--- gecode/search/pbs.cpp | 17 ++++---- gecode/search/pbs.hpp | 63 ++++++++++++++++++++-------- gecode/search/seq/pbs.hh | 14 ++++--- gecode/search/seq/pbs.hpp | 18 +++++--- gecode/search/seq/rbs.cpp | 5 +-- gecode/search/support.hh | 18 ++++---- test/search.cpp | 86 +++++++++++++++++++++++++++++++++++--- 13 files changed, 230 insertions(+), 89 deletions(-) diff --git a/changelog.in b/changelog.in index 84dfb8aeb9..25afe8b47f 100755 --- a/changelog.in +++ b/changelog.in @@ -116,7 +116,8 @@ Rank: minor End a portfolio when an asset exhausts its search space. [MORE] The exhausted asset proves that no further solution exists, so the other -assets no longer run until they are stopped. +assets no longer run until they are stopped. An asset whose spoke declares +SpokeCoverage::Partial is still dropped. [ENTRY] Module: search diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 9027192fa6..bcebdf7a3d 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -52,6 +52,7 @@ The return values become explicit decisions: | `master()` returns `false` after a solution | `hc.decision(MetaDecision::Continue)` | | `slave()` returns `true` | nothing, `SpokeCoverage::Full` is the default | | `slave()` returns `false` | `sc.coverage(SpokeCoverage::Partial)` | +| (none) | `sc.coverage(SpokeCoverage::Reduced)` | RBS honours `Continue` only after `MetaEvent::Solution`, just as it ignored `false` from `master()` after other events. To prove that no further @@ -60,15 +61,23 @@ solution exists, fail the hub. The coverage tells the engine what a spoke covers of the hub's search space: - `Full`: the spoke adds only branching and constraints that the hub - implies. Exhausting it is a proof. + implies. Exhausting it is a proof, and its no-goods hold in the hub. +- `Reduced`: the spoke prunes solutions but keeps one, or an optimal one, if + any exists, such as symmetry breaking. Exhausting it is a proof, but its + no-goods do not hold in the hub. Search for all solutions misses the + solutions that the spoke prunes. - `Partial`: the spoke searches part of the hub's search space, such as a - large neighbourhood. Exhausting it is no proof, and the no-goods - recorded while searching it do not reach `hub()`. + large neighbourhood. Exhausting it is no proof, and its no-goods do not + hold in the hub. The engine trusts the declared coverage. A spoke that declares more than it covers, such as `Full` for a spoke that removes solutions, gives undefined results. +`nogoods()` is empty unless the spoke of the episode that ended was `Full`. +PBS honours the coverage of each asset: an asset whose `Partial` spoke +exhausts is dropped instead of ending the portfolio. + The examples show typical overrides: - `examples/crossword.cpp`: a `hub()` that posts no-goods and continues diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 8e76dee801..cb837a61b3 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -1693,14 +1693,16 @@ namespace Gecode { Solution, ///< The episode found a solution /** * The episode exhausted its spoke. This is a proof only for a spoke - * of SpokeCoverage::Full, and then the engine has already ended: a - * hook only sees this event after a spoke of SpokeCoverage::Partial. + * of SpokeCoverage::Full or SpokeCoverage::Reduced, and then the + * engine has already ended: a hook only sees this event after a + * spoke of SpokeCoverage::Partial. */ Exhausted, /** * The inner engine ended without a proof (such as LDS). For a spoke - * of SpokeCoverage::Full, the engine has then already ended: a hook - * only sees this event after a spoke of SpokeCoverage::Partial. + * of SpokeCoverage::Full or SpokeCoverage::Reduced, the engine has + * then already ended: a hook only sees this event after a spoke of + * SpokeCoverage::Partial. */ Incomplete, Limit, ///< The episode reached the cutoff @@ -1725,8 +1727,7 @@ namespace Gecode { * * Space::spoke() declares the coverage of its spoke. It decides whether * exhausting the spoke proves that the hub has no further solution, and - * whether the no-goods recorded while searching the spoke hold in the - * hub. + * whether the no-goods recorded in the spoke hold in the hub. * * The engine trusts the declaration: a spoke that declares more coverage * than it has, such as a spoke that removes solutions but declares @@ -1735,12 +1736,20 @@ namespace Gecode { enum class SpokeCoverage : unsigned char { /** * The spoke adds only branching and constraints that the hub - * implies: exhaustion is a proof + * implies: exhaustion is a proof, and its no-goods hold in the hub */ Full, + /** + * The spoke prunes solutions but keeps one, or an optimal one, if + * any exists, such as symmetry breaking or dominance: exhaustion is + * a proof, but its no-goods do not hold in the hub. Search for all + * solutions misses the solutions that the spoke prunes. + */ + Reduced, /** * The spoke explores part of the hub's search space, such as a large - * neighbourhood search fragment: exhaustion is no proof + * neighbourhood search fragment: exhaustion is no proof, and its + * no-goods do not hold in the hub */ Partial, }; @@ -1814,9 +1823,8 @@ namespace Gecode { /** * \brief Return the no-goods of the finished episode * - * The no-goods are empty if the spoke of the episode has - * SpokeCoverage::Partial, as they only hold in the spoke's search - * space. + * Empty unless the spoke of that episode has SpokeCoverage::Full, so + * they can always be posted in the hub. */ const NoGoods& nogoods(void) const; }; @@ -2377,8 +2385,8 @@ namespace Gecode { * the spoke covers (see SpokeCoverage, the default is Full). Large * neighbourhood search, for example, fixes part of \a sc.last() and * declares SpokeCoverage::Partial. The no-goods recorded while - * searching a spoke of SpokeCoverage::Partial only hold in its - * search space, so RBS does not pass them to hub(). + * searching a spoke only hold in the hub for SpokeCoverage::Full, so + * RBS passes no no-goods to hub() for any other spoke. * * The default hook does nothing. * diff --git a/gecode/search.hh b/gecode/search.hh index b40565fed7..c1aa785530 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1627,12 +1627,15 @@ namespace Gecode { * (see Cutoff::copy()). If the constructor throws an exception, the * caller keeps the cutoff. * - * The spoke of each asset is taken to cover the search space of the - * hub. When an asset exhausts its search space, the portfolio ends and - * end_reason() returns Search::EndReason::Exhausted. An asset that ends - * without exhausting its search space, such as LDS at its discrepancy - * limit, is dropped while the other assets continue. When every asset - * has been dropped, end_reason() returns Search::EndReason::Incomplete. + * The spoke of each asset declares its coverage in Space::spoke() (see + * SpokeCoverage). When an asset whose spoke has SpokeCoverage::Full or + * SpokeCoverage::Reduced exhausts its search space, the portfolio ends + * and end_reason() returns Search::EndReason::Exhausted. An asset that + * ends without a proof is dropped while the other assets continue: an + * asset whose spoke has SpokeCoverage::Partial and exhausts its search + * space, or an engine such as LDS at its discrepancy limit. When every + * asset has been dropped, end_reason() returns + * Search::EndReason::Incomplete. * * The class \a T can override the member functions * \code virtual void hub(HubContext& hc) \endcode diff --git a/gecode/search/par/pbs.hh b/gecode/search/par/pbs.hh index a91559e679..b99626f23d 100644 --- a/gecode/search/par/pbs.hh +++ b/gecode/search/par/pbs.hh @@ -140,11 +140,15 @@ namespace Gecode { namespace Search { namespace Par { Engine* engine; /// Stop object Stop* stop; + /// Coverage of the spoke of the asset + SpokeCoverage _coverage; /// Whether the stop object of the asset stopped it during the current call to next() bool _parked; public: - /// Initialize with portfolio \a p, engine \a e, and its stop object \a so - Asset(PBS* p, Engine* e, Stop* so); + /// Initialize with portfolio \a p, engine \a e, its stop object \a so, and the coverage \a c of its spoke + Asset(PBS* p, Engine* e, Stop* so, SpokeCoverage c); + /// Return the coverage of the spoke of the asset + SpokeCoverage coverage(void) const; /// Return statistics of asset Statistics statistics(void) const; /// Return why the last call to next() of the asset returned no solution @@ -262,8 +266,9 @@ namespace Gecode { namespace Search { namespace Par { * - the assets n_active..n_assets-1 have ended without a proof. */ public: - /// Initialize - PBS(Engine** s, Stop** so, unsigned int n, const Statistics& stat); + /// Initialize with \a n assets, their stop objects, and the coverage of their spokes + PBS(Engine** s, Stop** so, const SpokeCoverage* c, unsigned int n, + const Statistics& stat); /// Return next solution (nullptr, if none exists or search has been stopped) virtual Space* next(void); /// Return statistics diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index 9d435e141f..01f811fe72 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -168,8 +168,14 @@ namespace Gecode { namespace Search { namespace Par { template forceinline - Asset::Asset(PBS* p, Engine* e, Stop* so) - : Support::Runnable(false), portfolio(p), engine(e), stop(so), _parked(false) {} + Asset::Asset(PBS* p, Engine* e, Stop* so, SpokeCoverage c) + : Support::Runnable(false), portfolio(p), engine(e), stop(so), + _coverage(c), _parked(false) {} + template + forceinline SpokeCoverage + Asset::coverage(void) const { + return _coverage; + } template forceinline Statistics Asset::statistics(void) const { @@ -225,15 +231,15 @@ namespace Gecode { namespace Search { namespace Par { template forceinline - PBS::PBS(Engine** engines, Stop** stops, unsigned int n, - const Statistics& stat0) + PBS::PBS(Engine** engines, Stop** stops, const SpokeCoverage* c, + unsigned int n, const Statistics& stat0) : stat(stat0), portfolio_stat(stat0,n), assets(heap.alloc*>(n)), n_assets(n), n_active(n), portfolio_stop(false), exhausted(false), end(EndReason::NotEnded), tostop(false), n_busy(0) { // Initialize assets for (unsigned int i=0U; i(this,engines[i],stops[i]); + assets[i] = new Asset(this,engines[i],stops[i],c[i]); static_cast(stops[i])->share(&tostop,&portfolio_stat,i); } } @@ -275,7 +281,7 @@ namespace Gecode { namespace Search { namespace Par { asset->parked(true); break; } - } else if (pbs_asset_proof(asset->end_reason())) { + } else if (pbs_asset_proof(asset->end_reason(),asset->coverage())) { // Stop the other assets, no further solution exists exhausted = true; tostop.store(true, std::memory_order_release); diff --git a/gecode/search/pbs.cpp b/gecode/search/pbs.cpp index 70116536ac..6bcaf91b4b 100644 --- a/gecode/search/pbs.cpp +++ b/gecode/search/pbs.cpp @@ -46,12 +46,13 @@ namespace Gecode { namespace Search { namespace Seq { } Engine* - pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, - const Statistics& stat, const Search::Options& opt, bool best) { + pbsengine(Engine** assets, Stop** stops, const SpokeCoverage* coverage, + unsigned int n_assets, const Statistics& stat, + const Search::Options& opt, bool best) { if (best) - return new PBS(assets,stops,n_assets,stat,opt); + return new PBS(assets,stops,coverage,n_assets,stat,opt); else - return new PBS(assets,stops,n_assets,stat,opt); + return new PBS(assets,stops,coverage,n_assets,stat,opt); } }}} @@ -73,12 +74,12 @@ namespace Gecode { namespace Search { namespace Par { } Engine* - pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, - const Statistics& stat, bool best) { + pbsengine(Engine** assets, Stop** stops, const SpokeCoverage* coverage, + unsigned int n_assets, const Statistics& stat, bool best) { if (best) - return new PBS(assets,stops,n_assets,stat); + return new PBS(assets,stops,coverage,n_assets,stat); else - return new PBS(assets,stops,n_assets,stat); + return new PBS(assets,stops,coverage,n_assets,stat); } }}} diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index 7b739b2b62..5c762cf492 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -158,14 +158,15 @@ namespace Gecode { namespace Search { hub.hub(hc); } - /// Run spoke() on the spoke \a s of asset \a i of \a n - forceinline void + /// Run spoke() on the spoke \a s of asset \a i of \a n and return its coverage + forceinline SpokeCoverage pbs_spoke(Space& s, unsigned int i, unsigned int n) { Statistics start; SpokeContext sc = MetaContextAccess::spoke(MetaEngine::Portfolio, MetaEvent::Start,0UL,i,n, nullptr,start,NoGoods::eng); s.spoke(sc); + return sc.coverage(); } /// A PBS engine builder @@ -206,8 +207,9 @@ namespace Gecode { namespace Search { namespace Seq { /// Create sequential portfolio engine GECODE_SEARCH_EXPORT Engine* - pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, - const Statistics& stat, const Search::Options& opt, bool best); + pbsengine(Engine** assets, Stop** stops, const SpokeCoverage* coverage, + unsigned int n_assets, const Statistics& stat, + const Search::Options& opt, bool best); }}} @@ -223,8 +225,8 @@ namespace Gecode { namespace Search { namespace Par { /// Create parallel portfolio engine GECODE_SEARCH_EXPORT Engine* - pbsengine(Engine** assets, Stop** stops, unsigned int n_assets, - const Statistics& stat, bool best); + pbsengine(Engine** assets, Stop** stops, const SpokeCoverage* coverage, + unsigned int n_assets, const Statistics& stat, bool best); }}} @@ -245,6 +247,7 @@ namespace Gecode { namespace Search { unsigned int n_assets = opt.assets; Engine** assets = r.alloc(n_assets); Stop** stops = r.alloc(n_assets); + SpokeCoverage* coverage = r.alloc(n_assets); for (unsigned int i=0U; iclone()); if (spoke.get() == hub) unowned_hub = nullptr; - pbs_spoke(*spoke,i,n_assets); + coverage[i] = pbs_spoke(*spoke,i,n_assets); std::unique_ptr c(pbs_cutoff >(cutoff)); if (c != nullptr) opt.cutoff = c.get(); @@ -271,7 +274,7 @@ namespace Gecode { namespace Search { (void) c.release(); } Engine* e = Seq::pbsengine( - assets,stops,n_assets,stat,opt,E::best); + assets,stops,coverage,n_assets,stat,opt,E::best); pbs_release_cutoff >(cutoff); return e; } catch (...) { @@ -289,6 +292,7 @@ namespace Gecode { namespace Search { int n_assets = sebs.size(); Engine** assets = r.alloc(n_assets); Stop** stops = r.alloc(n_assets); + SpokeCoverage* coverage = r.alloc(n_assets); for (int i=0; iclone()); if (spoke.get() == hub) unowned_hub = nullptr; - pbs_spoke(*spoke,static_cast(i), - static_cast(n_assets)); + coverage[i] = pbs_spoke(*spoke,static_cast(i), + static_cast(n_assets)); assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); builders_owned = false; return Seq::pbsengine( - assets,stops,static_cast(n_assets),stat,opt,best); + assets,stops,coverage,static_cast(n_assets),stat,opt, + best); } catch (...) { if (builders_owned) pbscleanup(sebs); @@ -347,6 +352,7 @@ namespace Gecode { namespace Search { Engine** assets = r.alloc(n_assets); Stop** stops = r.alloc(n_assets); + SpokeCoverage* coverage = r.alloc(n_assets); for (unsigned int i=0U; iclone()); if (spoke.get() == hub) unowned_hub = nullptr; - pbs_spoke(*spoke,i,n_assets); + coverage[i] = pbs_spoke(*spoke,i,n_assets); std::unique_ptr c(pbs_cutoff >(cutoff)); if (c != nullptr) opt.cutoff = c.get(); @@ -369,7 +375,8 @@ namespace Gecode { namespace Search { // The asset owns its cutoff (void) c.release(); } - Engine* e = Par::pbsengine(assets,stops,n_assets,stat,E::best); + Engine* e = Par::pbsengine(assets,stops,coverage,n_assets,stat, + E::best); pbs_release_cutoff >(cutoff); return e; } catch (...) { @@ -393,6 +400,7 @@ namespace Gecode { namespace Search { Engine** assets = r.alloc(n_assets); Stop** stops = r.alloc(n_assets); + SpokeCoverage* coverage = r.alloc(n_assets); for (int i=0; iclone()); if (spoke.get() == hub) unowned_hub = nullptr; - pbs_spoke(*spoke,static_cast(i), - static_cast(n_assets)); + coverage[i] = pbs_spoke(*spoke,static_cast(i), + static_cast(n_assets)); assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); builders_owned = false; return Par::pbsengine( - assets,stops,static_cast(n_assets),stat,best); + assets,stops,coverage,static_cast(n_assets),stat,best); } catch (...) { if (builders_owned) pbscleanup(sebs); @@ -470,10 +478,29 @@ namespace Gecode { // No need to create a portfolio engine but must run spoke function if (o.assets == 1) { std::unique_ptr seed(hub); - Search::pbs_spoke(*hub,0U,1U); + SpokeCoverage c = Search::pbs_spoke(*hub,0U,1U); // Retain the seed if a nested builder rejects its worker control. opt.clone = true; - e = Search::build(seed.get(),opt); + if (c != SpokeCoverage::Partial) { + e = Search::build(seed.get(),opt); + return; + } + // Only a portfolio engine reports an exhausted partial spoke as incomplete + std::unique_ptr stop(Search::Seq::pbsstop(nullptr,opt.stop)); + opt.stop = stop.get(); + // As for several assets, the asset owns a copy of the cutoff + Search::Cutoff* cutoff = opt.cutoff; + std::unique_ptr cc(Search::pbs_cutoff >(cutoff)); + if (cc != nullptr) + opt.cutoff = cc.get(); + std::unique_ptr asset(Search::build(seed.get(),opt)); + (void) cc.release(); + Search::Engine* a = asset.get(); + Search::Stop* so = stop.get(); + e = Search::Seq::pbsengine(&a,&so,&c,1U,stat,opt,E::best); + (void) asset.release(); + (void) stop.release(); + Search::pbs_release_cutoff >(cutoff); return; } diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index 87bafc751d..739fe81eae 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -81,6 +81,8 @@ namespace Gecode { namespace Search { namespace Seq { Engine* engine; /// Stop object Stop* stop; + /// Coverage of the spoke of the asset + SpokeCoverage _coverage; /// Whether the stop object of the asset stopped it during the current call to next() bool _parked; public: @@ -90,8 +92,10 @@ namespace Gecode { namespace Search { namespace Seq { Asset(const Asset& s) = default; /// Assignment operator Asset& operator =(const Asset& s) = default; - /// Initialize with engine \a e and its stop object \a so - void init(Engine* e, Stop* so); + /// Initialize with engine \a e, its stop object \a so, and the coverage \a c of its spoke + void init(Engine* e, Stop* so, SpokeCoverage c); + /// Return the coverage of the spoke of the asset + SpokeCoverage coverage(void) const; /// Return next solution Space* next(void); /// Return statistics of asset @@ -129,9 +133,9 @@ namespace Gecode { namespace Search { namespace Seq { /// Why the last call to next() returned no solution EndReason end; public: - /// Initialize - PBS(Engine** assets, Stop** stops, unsigned int n, - const Statistics& stat, const Search::Options& opt); + /// Initialize with \a n assets, their stop objects, and the coverage of their spokes + PBS(Engine** assets, Stop** stops, const SpokeCoverage* coverage, + unsigned int n, const Statistics& stat, const Search::Options& opt); /// Return next solution (nullptr, if none exists or search has been stopped) virtual Space* next(void); /// Return statistics diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index b7a66a9f35..64462dca0a 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -47,10 +47,16 @@ namespace Gecode { namespace Search { namespace Seq { forceinline Asset::Asset(void) - : engine(nullptr), stop(nullptr), _parked(false) {} + : engine(nullptr), stop(nullptr), _coverage(SpokeCoverage::Full), + _parked(false) {} forceinline void - Asset::init(Engine* e, Stop* so) { + Asset::init(Engine* e, Stop* so, SpokeCoverage c) { engine = e; stop = so; + _coverage = c; + } + forceinline SpokeCoverage + Asset::coverage(void) const { + return _coverage; } forceinline Space* Asset::next(void) { @@ -88,8 +94,8 @@ namespace Gecode { namespace Search { namespace Seq { template forceinline - PBS::PBS(Engine** e, Stop** s, unsigned int n, - const Statistics& stat0, + PBS::PBS(Engine** e, Stop** s, const SpokeCoverage* c, + unsigned int n, const Statistics& stat0, const Search::Options& opt) : stat(stat0), slice(opt.slice), assets(heap.alloc(n)), n_assets(n), cur(0), @@ -98,7 +104,7 @@ namespace Gecode { namespace Search { namespace Seq { ssi.l = opt.slice; for (unsigned int i=0U; i(s[i])); + assets[i].init(e[i],static_cast(s[i]),c[i]); static_cast(s[i])->share(&ssi); } } @@ -155,7 +161,7 @@ namespace Gecode { namespace Search { namespace Seq { n_parked++; } cur++; - } else if (pbs_asset_proof(asset_end)) { + } else if (pbs_asset_proof(asset_end,assets[cur].coverage())) { end = EndReason::Exhausted; return nullptr; } else { diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index ab80f7ef55..19de19c39d 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -66,9 +66,8 @@ namespace Gecode { namespace Search { namespace Seq { NoGoods& RBS::hub_nogoods(void) { - // The no-goods of a partial spoke only hold in its restricted search - // space, not in the hub. - if (coverage == SpokeCoverage::Partial) + // The no-goods hold in the hub only for a spoke of full coverage + if (coverage != SpokeCoverage::Full) return NoGoods::eng; NoGoods& ng = e->nogoods(); // Reset number of no-goods found diff --git a/gecode/search/support.hh b/gecode/search/support.hh index 44042cb16c..8fe8b72e9b 100644 --- a/gecode/search/support.hh +++ b/gecode/search/support.hh @@ -60,19 +60,17 @@ namespace Gecode { namespace Search { snapshot(Space* s, const Options& o); /** - * \brief Whether a portfolio asset that ended for reason \a r proves that - * the hub has no further solution + * \brief Whether a portfolio asset whose spoke has coverage \a c and that + * ended for reason \a r proves that the hub has no further solution * - * The spoke of every asset is taken to cover the search space of the - * hub, so an exhausted asset ends the portfolio with a proof. A spoke - * that covers only part of the search space, such as a fragment for - * large neighbourhood search, must not end the portfolio when it is - * exhausted: once spokes can declare their coverage, this is where it is - * taken into account. + * Only an asset that exhausted a spoke of full or reduced coverage ends + * the portfolio with a proof. An asset that exhausted a spoke of partial + * coverage, such as a fragment for large neighbourhood search, has proven + * nothing about the hub and is dropped. */ forceinline bool - pbs_asset_proof(EndReason r) { - return r == EndReason::Exhausted; + pbs_asset_proof(EndReason r, SpokeCoverage c) { + return (r == EndReason::Exhausted) && (c != SpokeCoverage::Partial); } /// Which stop object stopped an asset of a portfolio diff --git a/test/search.cpp b/test/search.cpp index 735591d9c4..6c1a4a8abc 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -905,6 +905,7 @@ namespace Test { RbsHubContinue, RbsHubRestart, RbsSpokeFull, + RbsSpokeReduced, RbsSpokePartial, RbsLimit, PbsHubOnly, @@ -982,8 +983,8 @@ namespace Test { holds(state.spoke_calls, restart ? 2U : 1U) && holds(state.hub_events, solution) && holds(state.spoke_events, start | (restart ? solution : 0U)); - } else if (solution_spoke_coverage == SpokeCoverage::Full) { - // Exhausting a spoke of full coverage is a proof + } else if (solution_spoke_coverage != SpokeCoverage::Partial) { + // Exhausting a spoke that is not partial is a proof ok = ok && (second == nullptr) && (search.end_reason() == EndReason::Exhausted) && holds(state.hub_calls, 1U) && holds(state.spoke_calls, 2U) && @@ -1228,6 +1229,8 @@ namespace Test { return rbs(MetaDecision::Restart, false, SpokeCoverage::Full); case Scenario::RbsSpokeFull: return rbs(MetaDecision::Restart, true, SpokeCoverage::Full); + case Scenario::RbsSpokeReduced: + return rbs(MetaDecision::Restart, true, SpokeCoverage::Reduced); case Scenario::RbsSpokePartial: return rbs(MetaDecision::Restart, true, SpokeCoverage::Partial); case Scenario::RbsLimit: @@ -2860,6 +2863,76 @@ namespace Test { } }; + /// Space whose spokes add constraints that keep some solution + class SatPreservingSpoke : public Gecode::Space { + public: + /// Coverage that spoke() declares + Gecode::SpokeCoverage coverage; + /// Variable with four values + Gecode::IntVar x; + /// Four variables with three values + Gecode::IntVarArray y; + /// Initialize with declared coverage \a c + SatPreservingSpoke(Gecode::SpokeCoverage c) + : coverage(c), x(*this,0,3), y(*this,4,0,2) { + Gecode::branch(*this,x,Gecode::INT_VAL_MIN()); + Gecode::branch(*this,y,Gecode::INT_VAR_NONE(),Gecode::INT_VAL_MIN()); + } + /// Clone \a s + SatPreservingSpoke(SatPreservingSpoke& s) + : Gecode::Space(s), coverage(s.coverage) { + x.update(*this,s.x); + y.update(*this,s.y); + } + Gecode::Space* copy(void) override { + return new SatPreservingSpoke(*this); + } + void spoke(Gecode::SpokeContext& sc) override { + // The y must be distinct, which is impossible, for x < 3 in the + // first episode and for x > 0 later: either keeps a solution + Gecode::BoolVar b = (sc.episode() == 0) ? + Gecode::expr(*this,x < 3) : Gecode::expr(*this,x > 0); + for (int i=0; i rbs(m,o); + delete m; + SatPreservingSpoke* s = rbs.next(); + r = rbs.end_reason(); + return s; + } + public: + RBSSpokeCoverage(void) : Base("Search::RBS::SpokeCoverage") {} + bool run(void) override { + EndReason r; + // Declared Reduced: no-goods stay in their spoke, x = 0 remains. + // These spokes are not Full, declaring them so is undefined. + SatPreservingSpoke* s = solve(Gecode::SpokeCoverage::Reduced,r); + const bool reduced = (s != nullptr) && (s->x.val() == 0); + delete s; + return reduced; + } + }; + + RBSSpokeCoverage rbs_spoke_coverage; + /// Space whose first spoke search is restricted to x2, x3 in {0,1} class RestrictedFirstSpoke : public Gecode::IntMinimizeSpace { public: @@ -2889,10 +2962,10 @@ namespace Test { } }; - /// No-goods from an incomplete spoke search are not posted in the hub - class RBSIncompleteNoGoods : public Base { + /// No-goods from a partial spoke search are not posted in the hub + class RBSPartialNoGoods : public Base { public: - RBSIncompleteNoGoods(void) : Base("Search::RBS::IncompleteNoGoods") {} + RBSPartialNoGoods(void) : Base("Search::RBS::PartialNoGoods") {} bool run(void) override { RestrictedFirstSpoke* m = new RestrictedFirstSpoke; Gecode::Search::Options o; @@ -2910,7 +2983,7 @@ namespace Test { } }; - RBSIncompleteNoGoods rbs_incomplete_nogoods; + RBSPartialNoGoods rbs_partial_nogoods; /// Space without solutions whose search tree has several failures class NoSolution : public Gecode::IntMinimizeSpace { @@ -3812,6 +3885,7 @@ namespace Test { (void)new MetaDispatch("RBS::HubContinue", MetaDispatch::Scenario::RbsHubContinue); (void)new MetaDispatch("RBS::HubRestart", MetaDispatch::Scenario::RbsHubRestart); (void)new MetaDispatch("RBS::SpokeFull", MetaDispatch::Scenario::RbsSpokeFull); + (void)new MetaDispatch("RBS::SpokeReduced", MetaDispatch::Scenario::RbsSpokeReduced); (void)new MetaDispatch("RBS::SpokePartial", MetaDispatch::Scenario::RbsSpokePartial); (void)new MetaDispatch("RBS::Limit", MetaDispatch::Scenario::RbsLimit); (void)new MetaDispatch("RBS::NoGoodsResetOwnership", From 911dfe4c2d3ecbd576a17a4e03e2fd62022e05ba Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 20:51:15 +0100 Subject: [PATCH 10/37] Constrain the hub with each solution in the engine For a best solution engine, restart-based search now constrains the hub with each solution before it calls hub(), instead of leaving it to the default hub(). An override that did not call the default lost the bound and found the same solutions again. The default hub() now only posts the no-goods. --- changelog.in | 11 +++ docs/gecode-7-migration.md | 8 +++ gecode/kernel/core.cpp | 2 - gecode/kernel/core.hpp | 10 ++- gecode/search.hh | 12 ++-- gecode/search/seq/rbs.cpp | 3 + test/search.cpp | 133 ++++++++++++++++++++++++++++++++++++- 7 files changed, 169 insertions(+), 10 deletions(-) diff --git a/changelog.in b/changelog.in index 25afe8b47f..d02ef2f387 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,17 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Constrain the hub of restart-based branch-and-bound search with each +solution in the engine itself. +[MORE] +The default hub() did it, so an override that did not call the default lost +the bound and found the same solutions again. + [ENTRY] Module: search What: change diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index bcebdf7a3d..a5eb1c5037 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -78,6 +78,14 @@ results. PBS honours the coverage of each asset: an asset whose `Partial` spoke exhausts is dropped instead of ending the portfolio. +Other changes to the hooks: + +- For a best solution engine such as `RBS`, the engine constrains + the hub with the last solution before it calls `hub()`. The default + `hub()` no longer calls `constrain()`, and an override that does not call + the default keeps the bound. For other engines, such as `RBS`, + RBS no longer calls `constrain()` at all. + The examples show typical overrides: - `examples/crossword.cpp`: a `hub()` that posts no-goods and continues diff --git a/gecode/kernel/core.cpp b/gecode/kernel/core.cpp index 728aa83c37..2632a32499 100644 --- a/gecode/kernel/core.cpp +++ b/gecode/kernel/core.cpp @@ -905,8 +905,6 @@ namespace Gecode { Space::hub(HubContext& hc) { switch (hc.engine()) { case MetaEngine::Restart: - if (hc.last() != nullptr) - constrain(*hc.last()); hc.nogoods().post(*this); break; case MetaEngine::Portfolio: diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index cb837a61b3..31edac311f 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -2363,9 +2363,13 @@ namespace Gecode { * the decision: failing the hub is how a hook declares that no * further solution exists. * - * The default hook constrains the hub with \a hc.last(), if any, and - * posts \a hc.nogoods() for RBS. For PBS, it removes all branchers, - * so spoke() must post the branching of each asset. + * In best solution search, RBS constrains the hub with each new + * solution before it calls hub(), so an override cannot lose the + * bound by not calling the default. + * + * The default hook posts \a hc.nogoods() for RBS. For PBS, it + * removes all branchers, so spoke() must post the branching of each + * asset. * * \ingroup TaskModelScript */ diff --git a/gecode/search.hh b/gecode/search.hh index c1aa785530..9c85a6a685 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1522,8 +1522,10 @@ namespace Gecode { * \code virtual void spoke(SpokeContext& sc) \endcode * * The engine calls hub() on its hub after solutions and at restarts, - * and spoke() on each spoke it clones from the hub. See Space::hub() - * and Space::spoke() for details. + * and spoke() on each spoke it clones from the hub. When \a E is a best + * solution engine, the engine constrains the hub by each solution + * before it calls hub(). See Space::hub() and Space::spoke() for + * details. * * \ingroup TaskModelSearch */ @@ -1554,8 +1556,10 @@ namespace Gecode { * \code virtual void spoke(SpokeContext& sc) \endcode * * The engine calls hub() on its hub after solutions and at restarts, - * and spoke() on each spoke it clones from the hub. See Space::hub() - * and Space::spoke() for details. + * and spoke() on each spoke it clones from the hub. When \a E is a best + * solution engine, the engine constrains the hub by each solution + * before it calls hub(). See Space::hub() and Space::spoke() for + * details. * * \ingroup TaskModelSearch */ diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index 19de19c39d..17fb8d3e16 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -77,6 +77,9 @@ namespace Gecode { namespace Search { namespace Seq { bool RBS::hub_event(MetaEvent ev) { + // Constrain the hub with a new solution, whatever hub() does + if ((ev == MetaEvent::Solution) && best) + hub->constrain(*last); Search::Statistics episode_stat = e->statistics(); NoGoods& ng = hub_nogoods(); HubContext hc = MetaContextAccess::hub(MetaEngine::Restart,ev,episode, diff --git a/test/search.cpp b/test/search.cpp index 6c1a4a8abc..e54c32d2c6 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -52,6 +52,7 @@ #include #include #include +#include #include static_assert(std::is_copy_constructible::value, @@ -1072,7 +1073,8 @@ namespace Test { o.nogoods_limit = 16; o.stop = &stop; o.cutoff = Gecode::Search::Cutoff::constant(1); - Gecode::RBS search(m, o); + // The engine constrains the hub by each solution + Gecode::RBS search(m, o); delete m; unsigned int solutions = 0; @@ -3679,6 +3681,135 @@ namespace Test { PBSRestartCutoff pbs_restart_cutoff; + /// Hook behaviour of ProtocolSpace + enum class Protocol { + Default, ///< Default hooks + EmptyHub, ///< hub() does nothing + }; + + /// Calls of the hooks of ProtocolSpace + struct ProtocolLog { + /// Event and episode of each hub() call + std::vector > hub; + /// Event and episode of each spoke() call + std::vector > spoke; + /// Number of spaces alive + std::atomic live{0}; + }; + + /// Space whose hooks follow a Protocol + class ProtocolSpace : public IntMinimizeSpace { + public: + /// Hook behaviour + Protocol protocol; + /// Log of hook calls + ProtocolLog* log; + /// Cost + IntVar c; + /// Whether the y must be distinct, which is impossible + BoolVar p; + /// Four variables with three values + IntVarArray y; + /// Initialize with hook behaviour \a pr and log \a l + ProtocolSpace(Protocol pr, ProtocolLog& l) + : protocol(pr), log(&l), c(*this,0,3), p(*this,0,1), y(*this,4,0,2) { + log->live++; + for (int i=0; ilive++; + c.update(*this,s.c); + p.update(*this,s.p); + y.update(*this,s.y); + } + /// Record destruction + ~ProtocolSpace(void) override { + log->live--; + } + Space* copy(void) override { + return new ProtocolSpace(*this); + } + IntVar cost(void) const override { + return c; + } + void hub(HubContext& hc) override { + log->hub.emplace_back(hc.event(),hc.episode()); + switch (protocol) { + case Protocol::EmptyHub: + return; + case Protocol::Default: + break; + } + IntMinimizeSpace::hub(hc); + } + void spoke(SpokeContext& sc) override { + log->spoke.emplace_back(sc.event(),sc.episode()); + } + }; + + /// Decisions, events, and ends of the meta search protocol + class MetaProtocol : public Base { + public: + /// Scenario + enum class Scenario { + EngineConstrainsHub, + }; + protected: + /// Scenario under test + Scenario scenario; + /// Return options for RBS with constant cutoff \a c + static Gecode::Search::Options rbs_options(unsigned long int c) { + Gecode::Search::Options o; + o.threads = 1; + o.cutoff = Gecode::Search::Cutoff::constant(c); + return o; + } + /// Check that RBS constrains the hub when hub() does nothing + static bool engine_constrains_hub(void) { + ProtocolLog log; + std::vector costs; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::EmptyHub,log); + Gecode::RBS rbs(m,rbs_options(100)); + delete m; + // Without the bound, every spoke finds c = 3 again + while (ProtocolSpace* s = rbs.next()) { + costs.push_back(s->c.val()); + delete s; + if (costs.size() > 10U) + return false; + } + if (rbs.end_reason() != EndReason::Exhausted) + return false; + } + return (costs == std::vector{3,2,1,0}) && (log.live == 0); + } + public: + /// Initialize scenario \a s with name \a n + MetaProtocol(const std::string& n, Scenario s) + : Base("Search::Meta::"+n), scenario(s) {} + bool run(void) override { + switch (scenario) { + case Scenario::EngineConstrainsHub: + return engine_constrains_hub(); + default: + GECODE_NEVER; + } + return false; + } + }; + + MetaProtocol meta_engine_constrains_hub + ("EngineConstrainsHub",MetaProtocol::Scenario::EngineConstrainsHub); + /** * \brief Constant cutoff counting its deletions * From f8b43da03e7e8b0a8210603515bac773811f717e Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 20:54:59 +0100 Subject: [PATCH 11/37] Propagate the hub of portfolio search and require spoke branchers Portfolio search now calls status() on the hub after hub() and before it clones the spokes. A hub() that posted a constraint made the portfolio throw SpaceNotStable, and a hub that fails now ends the portfolio as exhausted. After spoke(), a spoke without branchers throws Search::SpokeNoBrancher when the hub had branchers. The default hub() removes all branchers, so a spoke() that forgot to post the branching of its asset returned the unassigned spoke as a solution. --- changelog.in | 21 ++++++++ docs/gecode-7-migration.md | 6 +++ gecode/kernel/core.hpp | 5 +- gecode/search.hh | 16 +++--- gecode/search/exception.cpp | 4 ++ gecode/search/exception.hpp | 6 +++ gecode/search/pbs.hpp | 90 +++++++++++++++++++++++++--------- test/search.cpp | 98 ++++++++++++++++++++++++++++++------- 8 files changed, 198 insertions(+), 48 deletions(-) diff --git a/changelog.in b/changelog.in index d02ef2f387..da415be616 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,27 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: change +Rank: minor +[DESCRIPTION] +Throw Search::SpokeNoBrancher when a spoke of portfolio search has no +brancher but the hub had branchers. +[MORE] +The default hub() removes all branchers, so a spoke() that forgot to post +the branching of its asset returned the unassigned spoke as a solution. + +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Propagate the hub of portfolio search after hub() and before cloning the +spokes. +[MORE] +A hub() that posted a constraint made the portfolio throw SpaceNotStable. + [ENTRY] Module: search What: bug diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index a5eb1c5037..ffa0997471 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -85,6 +85,12 @@ Other changes to the hooks: `hub()` no longer calls `constrain()`, and an override that does not call the default keeps the bound. For other engines, such as `RBS`, RBS no longer calls `constrain()` at all. +- PBS calls `status()` on the hub after `hub()`, so `hub()` can post + constraints. In Gecode 6, cloning such a hub threw `SpaceNotStable`. +- The default PBS `hub()` still removes all branchers, so `spoke()` must post + the branching of each asset. When the hub had branchers but a spoke has + none after `spoke()`, PBS throws `Search::SpokeNoBrancher` instead of + returning the unassigned spoke as a solution. The examples show typical overrides: diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 31edac311f..5165470ddc 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -2359,7 +2359,7 @@ namespace Gecode { * * The hook may post constraints in the hub and sets what the engine * does next with \a hc.decision() (see MetaDecision). If the hub - * fails, RBS ends with Search::EndReason::Exhausted whatever + * fails, the engine ends with Search::EndReason::Exhausted whatever * the decision: failing the hub is how a hook declares that no * further solution exists. * @@ -2392,6 +2392,9 @@ namespace Gecode { * searching a spoke only hold in the hub for SpokeCoverage::Full, so * RBS passes no no-goods to hub() for any other spoke. * + * PBS throws Search::SpokeNoBrancher if the hub had branchers before + * hub() and a spoke that has not failed has none after spoke(). + * * The default hook does nothing. * * \ingroup TaskModelScript diff --git a/gecode/search.hh b/gecode/search.hh index 9c85a6a685..0dccb78284 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1646,9 +1646,11 @@ namespace Gecode { * and * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() once on its hub with MetaEvent::Start and then - * spoke() on the spoke of each asset. See Space::hub() and - * Space::spoke() for details. + * The engine calls hub() once on its hub with MetaEvent::Start, then + * Space::status() on the hub, and then spoke() on the spoke of each + * asset. When the hub had branchers before hub() but a spoke has none + * after spoke(), the engine throws Search::SpokeNoBrancher. See + * Space::hub() and Space::spoke() for details. * * \ingroup TaskModelSearch */ @@ -1702,9 +1704,11 @@ namespace Gecode { * and * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() once on its hub with MetaEvent::Start and then - * spoke() on the spoke of each asset. See Space::hub() and - * Space::spoke() for details. + * The engine calls hub() once on its hub with MetaEvent::Start, then + * Space::status() on the hub, and then spoke() on the spoke of each + * asset. When the hub had branchers before hub() but a spoke has none + * after spoke(), the engine throws Search::SpokeNoBrancher. See + * Space::hub() and Space::spoke() for details. * * \ingroup TaskModelSearch */ diff --git a/gecode/search/exception.cpp b/gecode/search/exception.cpp index 8e3bcb8974..f1a36df33e 100644 --- a/gecode/search/exception.cpp +++ b/gecode/search/exception.cpp @@ -52,6 +52,10 @@ namespace Gecode { namespace Search { : Exception(l,"Illegal combination of best and non-best solution search") {} + SpokeNoBrancher::SpokeNoBrancher(const char* l) + : Exception(l,"Spoke of a portfolio has no brancher, but the hub had " + "branchers") {} + NoBest::NoBest(const char* l) : Exception(l,"Best solution search is not supported") {} diff --git a/gecode/search/exception.hpp b/gecode/search/exception.hpp index 16b65661f1..dc7ff26dc3 100644 --- a/gecode/search/exception.hpp +++ b/gecode/search/exception.hpp @@ -56,6 +56,12 @@ namespace Gecode { namespace Search { /// Initialize with location \a l MixedBest(const char* l); }; + /// %Exception: Portfolio spoke without brancher although the hub had branchers + class GECODE_SEARCH_EXPORT SpokeNoBrancher : public Exception { + public: + /// Initialize with location \a l + SpokeNoBrancher(const char* l); + }; /// %Exception: Best solution search is not supported class GECODE_SEARCH_EXPORT NoBest : public Exception { public: diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index 5c762cf492..7d7426d549 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -148,24 +148,46 @@ namespace Gecode { namespace Search { delete c; } - /// Run hub() with MetaEvent::Start on the hub \a hub of a portfolio of \a n assets - forceinline void - pbs_hub(Space& hub, unsigned int n) { + /** + * \brief Run hub() with MetaEvent::Start on the hub \a hub of a portfolio + * of \a n assets and propagate it + * + * Return whether the portfolio must be built. Otherwise the hub has + * failed and \a hub is deleted. + */ + template + bool + pbs_start(T* hub, unsigned int n, Statistics& stat) { + std::unique_ptr owned(hub); Statistics start; HubContext hc = MetaContextAccess::hub(MetaEngine::Portfolio, MetaEvent::Start,0UL,0U,n, nullptr,start,NoGoods::eng); - hub.hub(hc); + hub->hub(hc); + if (hub->status(stat) == SS_FAILED) { + stat.fail++; + return false; + } + (void) owned.release(); + return true; } - /// Run spoke() on the spoke \a s of asset \a i of \a n and return its coverage + /** + * \brief Run spoke() on the spoke \a s of asset \a i of \a n and return + * its coverage + * + * Throw SpokeNoBrancher if the hub had branchers (\a hub_branchers) and + * \a s has none, as the spoke would then be taken as a solution. + */ forceinline SpokeCoverage - pbs_spoke(Space& s, unsigned int i, unsigned int n) { + pbs_spoke(Space& s, unsigned int i, unsigned int n, bool hub_branchers) { Statistics start; SpokeContext sc = MetaContextAccess::spoke(MetaEngine::Portfolio, MetaEvent::Start,0UL,i,n, nullptr,start,NoGoods::eng); s.spoke(sc); + if (hub_branchers && !s.failed() && (BrancherGroup::all.size(s) == 0U)) + throw SpokeNoBrancher("PBS::PBS"); return sc.coverage(); } @@ -234,7 +256,8 @@ namespace Gecode { namespace Search { template class E> Engine* - pbsseq(T* hub, const Search::Statistics& stat, Options& opt) { + pbsseq(T* hub, const Search::Statistics& stat, Options& opt, + bool hub_branchers) { Stop* stop = opt.stop; // Retain each seed: a throwing nested builder may consume its own clone. opt.clone = true; @@ -265,7 +288,7 @@ namespace Gecode { namespace Search { hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; - coverage[i] = pbs_spoke(*spoke,i,n_assets); + coverage[i] = pbs_spoke(*spoke,i,n_assets,hub_branchers); std::unique_ptr c(pbs_cutoff >(cutoff)); if (c != nullptr) opt.cutoff = c.get(); @@ -286,7 +309,8 @@ namespace Gecode { namespace Search { template class E> Engine* pbsseq(T* hub, SEBs& sebs, - const Search::Statistics& stat, Options& opt, bool best) { + const Search::Statistics& stat, Options& opt, bool best, + bool hub_branchers) { Region r; int n_assets = sebs.size(); @@ -315,7 +339,8 @@ namespace Gecode { namespace Search { if (spoke.get() == hub) unowned_hub = nullptr; coverage[i] = pbs_spoke(*spoke,static_cast(i), - static_cast(n_assets)); + static_cast(n_assets), + hub_branchers); assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); @@ -336,7 +361,8 @@ namespace Gecode { namespace Search { template class E> Engine* - pbspar(T* hub, const Search::Statistics& stat, Options& opt) { + pbspar(T* hub, const Search::Statistics& stat, Options& opt, + bool hub_branchers) { Stop* stop = opt.stop; // Retain each seed: a throwing nested builder may consume its own clone. opt.clone = true; @@ -367,7 +393,7 @@ namespace Gecode { namespace Search { hub : hub->clone()); if (spoke.get() == hub) unowned_hub = nullptr; - coverage[i] = pbs_spoke(*spoke,i,n_assets); + coverage[i] = pbs_spoke(*spoke,i,n_assets,hub_branchers); std::unique_ptr c(pbs_cutoff >(cutoff)); if (c != nullptr) opt.cutoff = c.get(); @@ -388,7 +414,8 @@ namespace Gecode { namespace Search { template class E> Engine* pbspar(T* hub, SEBs& sebs, - const Search::Statistics& stat, Options& opt, bool best) { + const Search::Statistics& stat, Options& opt, bool best, + bool hub_branchers) { Region r; // Run every asset in its own thread, even with fewer threads than assets @@ -420,7 +447,8 @@ namespace Gecode { namespace Search { if (spoke.get() == hub) unowned_hub = nullptr; coverage[i] = pbs_spoke(*spoke,static_cast(i), - static_cast(n_assets)); + static_cast(n_assets), + hub_branchers); assets[i] = (*sebs[i])(spoke.get()); } pbscleanup(sebs); @@ -472,13 +500,17 @@ namespace Gecode { dynamic_cast(s->clone()) : s; opt.clone = false; - // Always execute hub function - Search::pbs_hub(*hub,opt.assets); + bool hub_branchers = BrancherGroup::all.size(*hub) > 0U; + if (!Search::pbs_start(hub,opt.assets,stat)) { + e = Search::Seq::dead(opt,stat); + Search::pbs_release_cutoff >(opt.cutoff); + return; + } // No need to create a portfolio engine but must run spoke function if (o.assets == 1) { std::unique_ptr seed(hub); - SpokeCoverage c = Search::pbs_spoke(*hub,0U,1U); + SpokeCoverage c = Search::pbs_spoke(*hub,0U,1U,hub_branchers); // Retain the seed if a nested builder rejects its worker control. opt.clone = true; if (c != SpokeCoverage::Partial) { @@ -506,10 +538,10 @@ namespace Gecode { #ifdef GECODE_HAS_THREADS if (opt.threads > 1.0) - e = Search::pbspar(hub,stat,opt); + e = Search::pbspar(hub,stat,opt,hub_branchers); else #endif - e = Search::pbsseq(hub,stat,opt); + e = Search::pbsseq(hub,stat,opt,hub_branchers); } template class E> @@ -545,15 +577,27 @@ namespace Gecode { dynamic_cast(s->clone()) : s; opt.clone = false; - // Always execute hub function - Search::pbs_hub(*hub,static_cast(sebs.size())); + bool hub_branchers = BrancherGroup::all.size(*hub) > 0U; + bool started; + try { + started = Search::pbs_start(hub,static_cast(sebs.size()), + stat); + } catch (...) { + Search::pbscleanup(sebs); + throw; + } + if (!started) { + Search::pbscleanup(sebs); + e = Search::Seq::dead(opt,stat); + return; + } #ifdef GECODE_HAS_THREADS if (opt.threads > 1.0) - e = Search::pbspar(hub,sebs,stat,opt,best); + e = Search::pbspar(hub,sebs,stat,opt,best,hub_branchers); else #endif - e = Search::pbsseq(hub,sebs,stat,opt,best); + e = Search::pbsseq(hub,sebs,stat,opt,best,hub_branchers); } template class E> diff --git a/test/search.cpp b/test/search.cpp index e54c32d2c6..cb251050c5 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -701,6 +701,8 @@ namespace Test { SpokeCoverage solution_spoke_coverage = SpokeCoverage::Full; bool fail_solution_spoke = false; bool nogood_model = false; + /// Whether the model posts a branching on x + bool model_branching = true; /// Whether a PBS spoke() posts the branching for its asset bool spoke_branching = true; /// Whether the first RBS spoke reaches the cutoff without a solution @@ -779,7 +781,8 @@ namespace Test { distinct(*this, q, IPL_VAL); Gecode::branch(*this, q, INT_VAR_NONE(), INT_VAL_MIN()); } - Gecode::branch(*this, x, INT_VAL_MIN()); + if (state->model_branching) + Gecode::branch(*this, x, INT_VAL_MIN()); } /// Clone \a s MetaDispatchSpace(MetaDispatchSpace& s) @@ -919,7 +922,8 @@ namespace Test { PbsParallelSpokeOnly, PbsParallel, PbsParallelThreadLimit, - PbsDefaultHubRemovesBranchers, + PbsSpokeWithoutBrancher, + PbsNoBrancher, RbsNoGoodsResetOwnership, MetaStopOwnership, BabIncumbent @@ -1018,23 +1022,29 @@ namespace Test { delete solution; return ok; } - /// Check that the default PBS hub() removes the model's branching + /// Check that PBS rejects a spoke without branching when the hub had one static bool - pbs_default_hub_removes_branchers(void) { + pbs_spoke_without_brancher(bool model_branching) { MetaDispatchState state; state.spoke_branching = false; + state.model_branching = model_branching; SpokeDispatchSpace* m = new SpokeDispatchSpace(state); Gecode::Search::Options o; o.assets = 3; o.threads = 1; - Gecode::PBS search(m, o); - delete m; - - // A spoke without branching is a solution as soon as it is stable. - SpokeDispatchSpace* solution = search.next(); - bool ok = (solution != nullptr) && !solution->assigned() && holds(state.spoke_calls, 3U); - delete solution; - return ok; + try { + Gecode::PBS search(m, o); + delete m; + // A spoke without branching is a solution as soon as it is stable. + SpokeDispatchSpace* solution = search.next(); + bool ok = !model_branching && (solution != nullptr) && !solution->assigned() && + holds(state.spoke_calls, 3U); + delete solution; + return ok; + } catch (const Gecode::Search::SpokeNoBrancher&) { + delete m; + return model_branching && holds(state.live_spaces, 0U); + } } /// Check RBS dispatch when the first spoke reaches the cutoff static bool @@ -1258,8 +1268,10 @@ namespace Test { case Scenario::PbsParallelThreadLimit: // Parallel PBS runs all assets, also with fewer threads. return pbs(3, 2, 1, 3, 7); - case Scenario::PbsDefaultHubRemovesBranchers: - return pbs_default_hub_removes_branchers(); + case Scenario::PbsSpokeWithoutBrancher: + return pbs_spoke_without_brancher(true); + case Scenario::PbsNoBrancher: + return pbs_spoke_without_brancher(false); case Scenario::RbsNoGoodsResetOwnership: return rbs_nogoods_reset_ownership(); case Scenario::MetaStopOwnership: @@ -1845,6 +1857,11 @@ namespace Test { constraints->fetch_add(1); IntMinimizeSpace::constrain(s); } + virtual void hub(HubContext& hc) { + // Keep the branchers for the assets of a portfolio + if (hc.engine() == MetaEngine::Restart) + Space::hub(hc); + } }; /// Small objective whose solutions arrive from worst to best @@ -3683,8 +3700,9 @@ namespace Test { /// Hook behaviour of ProtocolSpace enum class Protocol { - Default, ///< Default hooks - EmptyHub, ///< hub() does nothing + Default, ///< Default hooks + EmptyHub, ///< hub() does nothing + BoundInHub, ///< hub() posts c <= 1 at Start and keeps the branchers }; /// Calls of the hooks of ProtocolSpace @@ -3745,6 +3763,12 @@ namespace Test { switch (protocol) { case Protocol::EmptyHub: return; + case Protocol::BoundInHub: + if (hc.event() == MetaEvent::Start) { + rel(*this,c,IRT_LQ,1); + return; + } + break; case Protocol::Default: break; } @@ -3761,6 +3785,7 @@ namespace Test { /// Scenario enum class Scenario { EngineConstrainsHub, + PortfolioHubConstraint, }; protected: /// Scenario under test @@ -3792,6 +3817,39 @@ namespace Test { } return (costs == std::vector{3,2,1,0}) && (log.live == 0); } + /// Check that a constraint posted by hub() under PBS takes effect + static bool portfolio_hub_constraint(void) { + ProtocolLog log; + for (unsigned int t : {1U,2U}) { + ProtocolSpace* m = new ProtocolSpace(Protocol::BoundInHub,log); + Gecode::Search::Options o; + o.assets = 2; + o.threads = t; + Gecode::PBS pbs(m,o); + delete m; + ProtocolSpace* s = pbs.next(); + const bool ok = (s != nullptr) && (s->c.val() == 1); + delete s; + if (!ok) + return false; + } + { + ProtocolSpace* m = new ProtocolSpace(Protocol::BoundInHub,log); + Gecode::Search::Options o; + o.threads = 1; + SEBs assets(2); + for (int i=0; i<2; i++) + assets[i] = Gecode::dfs(o); + Gecode::PBS pbs(m,assets,o); + delete m; + ProtocolSpace* s = pbs.next(); + const bool ok = (s != nullptr) && (s->c.val() == 1); + delete s; + if (!ok) + return false; + } + return log.live == 0; + } public: /// Initialize scenario \a s with name \a n MetaProtocol(const std::string& n, Scenario s) @@ -3800,6 +3858,8 @@ namespace Test { switch (scenario) { case Scenario::EngineConstrainsHub: return engine_constrains_hub(); + case Scenario::PortfolioHubConstraint: + return portfolio_hub_constraint(); default: GECODE_NEVER; } @@ -3809,6 +3869,8 @@ namespace Test { MetaProtocol meta_engine_constrains_hub ("EngineConstrainsHub",MetaProtocol::Scenario::EngineConstrainsHub); + MetaProtocol meta_portfolio_hub_constraint + ("PortfolioHubConstraint",MetaProtocol::Scenario::PortfolioHubConstraint); /** * \brief Constant cutoff counting its deletions @@ -4041,8 +4103,8 @@ namespace Test { (void)new MetaDispatch("PBS::SequentialHubOnly", MetaDispatch::Scenario::PbsSequentialHubOnly); (void)new MetaDispatch("PBS::SequentialSpokeOnly", MetaDispatch::Scenario::PbsSequentialSpokeOnly); (void)new MetaDispatch("PBS::Sequential", MetaDispatch::Scenario::PbsSequential); - (void)new MetaDispatch("PBS::DefaultHubRemovesBranchers", - MetaDispatch::Scenario::PbsDefaultHubRemovesBranchers); + (void)new MetaDispatch("PBS::SpokeWithoutBrancher", MetaDispatch::Scenario::PbsSpokeWithoutBrancher); + (void)new MetaDispatch("PBS::NoBrancher", MetaDispatch::Scenario::PbsNoBrancher); #ifdef GECODE_HAS_THREADS (void)new MetaDispatch("PBS::ParallelHubOnly", MetaDispatch::Scenario::PbsParallelHubOnly); (void)new MetaDispatch("PBS::ParallelSpokeOnly", MetaDispatch::Scenario::PbsParallelSpokeOnly); From 62cca9a15d0b5da91204c6da5fdec3969373d7ec Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 21:05:42 +0100 Subject: [PATCH 12/37] Add the Finish decision and per-event defaults for meta search hub() can now set MetaDecision::Finish to end restart-based search as incomplete, and Continue after MetaEvent::Limit to resume the same spoke with the next cutoff as a fresh budget. A decision that is illegal for the event throws IllegalMetaDecision, and HubContext::legal() tells which decisions are legal. Restart-based search calls hub() with Start before the first spoke, and after every episode that does not end with a proof, also when the inner engine of a Full or Reduced spoke ends incomplete. The engine sets a default decision for each event: Restart, except Finish after an Incomplete episode whose spoke is not Partial, since a new spoke would repeat the same search. A restart is counted when the engine restarts, after hub() returns and the hub is not failed. --- changelog.in | 6 +- docs/gecode-7-migration.md | 16 +- gecode/kernel/core.hpp | 95 ++++++---- gecode/kernel/exception.cpp | 3 + gecode/kernel/exception.hpp | 7 + gecode/search.hh | 20 +- gecode/search/pbs.hpp | 34 ++-- gecode/search/rbs.hpp | 19 +- gecode/search/seq/dead.cpp | 22 ++- gecode/search/seq/dead.hh | 3 +- gecode/search/seq/rbs.cpp | 86 +++++---- gecode/search/seq/rbs.hh | 2 + gecode/search/seq/rbs.hpp | 7 + test/search.cpp | 369 ++++++++++++++++++++++++++++++++++-- 14 files changed, 562 insertions(+), 127 deletions(-) diff --git a/changelog.in b/changelog.in index da415be616..57964abf3f 100755 --- a/changelog.in +++ b/changelog.in @@ -191,8 +191,10 @@ Replace the meta-search Space hooks master() and slave() and the class MetaInfo by hub(HubContext&) and spoke(SpokeContext&). [MORE] hub() sets a MetaDecision and spoke() declares a SpokeCoverage instead of -returning a Boolean. There are no compatibility aliases, also not for the -FlatZincSpace override of slave(). See docs/gecode-7-migration.md. +returning a Boolean. Restart-based search also calls hub() when search +starts and after an episode that ends without a proof. There are no +compatibility aliases, also not for the FlatZincSpace override of slave(). +See docs/gecode-7-migration.md. [ENTRY] Module: search diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index ffa0997471..131d1b54b1 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -50,13 +50,16 @@ The return values become explicit decisions: |----------------------------------------|--------------------------------------------------------| | `master()` returns `true` | `hc.decision(MetaDecision::Restart)`, the default | | `master()` returns `false` after a solution | `hc.decision(MetaDecision::Continue)` | +| (none) | `hc.decision(MetaDecision::Continue)` after a limit | +| (none) | `hc.decision(MetaDecision::Finish)` | | `slave()` returns `true` | nothing, `SpokeCoverage::Full` is the default | | `slave()` returns `false` | `sc.coverage(SpokeCoverage::Partial)` | | (none) | `sc.coverage(SpokeCoverage::Reduced)` | -RBS honours `Continue` only after `MetaEvent::Solution`, just as it ignored -`false` from `master()` after other events. To prove that no further -solution exists, fail the hub. +`Continue` is only legal after `MetaEvent::Solution` and `MetaEvent::Limit`; +setting it for another event throws `IllegalMetaDecision`. `Finish` ends the +engine with `EndReason::Incomplete`. To prove that no further solution +exists, fail the hub. The coverage tells the engine what a spoke covers of the hub's search space: @@ -80,11 +83,18 @@ exhausts is dropped instead of ending the portfolio. Other changes to the hooks: +- RBS calls `hub()` with `MetaEvent::Start` before it clones the first + spoke. Gecode 6 did not call `master()` then. - For a best solution engine such as `RBS`, the engine constrains the hub with the last solution before it calls `hub()`. The default `hub()` no longer calls `constrain()`, and an override that does not call the default keeps the bound. For other engines, such as `RBS`, RBS no longer calls `constrain()` at all. +- After an episode that ends without a proof, such as LDS at its + discrepancy limit, RBS calls `hub()` with `MetaEvent::Incomplete`. By + default, it finishes when the spoke was `Full` or `Reduced`, as a new + spoke would repeat the same search, and restarts when it was `Partial`. + Both `Restart` and `Finish` are legal. - PBS calls `status()` on the hub after `hub()`, so `hub()` can post constraints. In Gecode 6, cloning such a hub threw `SpaceNotStable`. - The default PBS `hub()` still removes all branchers, so `spoke()` must post diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 5165470ddc..3dc0bd1519 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -1698,28 +1698,43 @@ namespace Gecode { * spoke of SpokeCoverage::Partial. */ Exhausted, - /** - * The inner engine ended without a proof (such as LDS). For a spoke - * of SpokeCoverage::Full or SpokeCoverage::Reduced, the engine has - * then already ended: a hook only sees this event after a spoke of - * SpokeCoverage::Partial. - */ - Incomplete, - Limit, ///< The episode reached the cutoff + Incomplete, ///< The inner engine ended without a proof (such as LDS) + Limit, ///< The episode reached the cutoff }; /** * \brief What a meta search engine does after Space::hub() returns * - * The default is \c Restart. RBS honours \c Continue only after - * MetaEvent::Solution and restarts after any other event. PBS calls - * hub() only with MetaEvent::Start and ignores the decision. + * The engine sets the default before it calls hub(). Which decisions are + * legal depends on the event: + * + * | Event | Restart | Continue | Finish | + * |---------------|-----------|----------|-----------| + * | \c Start | default | illegal | legal | + * | \c Solution | default | legal | legal | + * | \c Limit | default | legal | legal | + * | \c Exhausted | default | illegal | legal | + * | \c Incomplete | see below | illegal | see below | + * + * After \c Incomplete, the default is \c Finish when the spoke of the + * episode has SpokeCoverage::Full or SpokeCoverage::Reduced, as a new + * spoke would repeat the same search, and \c Restart when it has + * SpokeCoverage::Partial. + * + * Setting an illegal decision throws IllegalMetaDecision. PBS calls + * hub() only with MetaEvent::Start. */ enum class MetaDecision : unsigned char { - /// Search a new spoke + /// Search a new spoke (at \c Start: start search) Restart, - /// Continue the current episode: search the same spoke for the next solution + /** + * Continue the current episode: after \c Solution, search the same + * spoke for the next solution; after \c Limit, resume the same spoke + * with the next cutoff as a fresh budget + */ Continue, + /// End the engine: next() returns nullptr with EndReason::Incomplete + Finish, }; /** @@ -1835,9 +1850,11 @@ namespace Gecode { protected: /// The decision MetaDecision _decision; + /// Whether decision \a d is legal for event \a e (see MetaDecision) + static bool legal(MetaEvent e, MetaDecision d); private: - /// Initialize with decision MetaDecision::Restart - HubContext(MetaEngine engine, MetaEvent event, + /// Initialize with the default decision \a d + HubContext(MetaEngine engine, MetaEvent event, MetaDecision d, unsigned long int episode, unsigned int asset, unsigned int assets, const Space* last, const Search::Statistics& statistics, @@ -1845,7 +1862,12 @@ namespace Gecode { public: /// Return the decision MetaDecision decision(void) const; - /// Set the decision to \a d, the last one set counts + /** + * \brief Set the decision to \a d, the last one set counts + * + * Throws IllegalMetaDecision if \a d is illegal for the event (see + * MetaDecision). + */ void decision(MetaDecision d); }; @@ -1879,9 +1901,9 @@ namespace Gecode { */ class MetaContextAccess { public: - /// Return a context for Space::hub() with decision MetaDecision::Restart + /// Return a context for Space::hub() with the default decision \a d static HubContext hub(MetaEngine engine, MetaEvent event, - unsigned long int episode, + MetaDecision d, unsigned long int episode, unsigned int asset, unsigned int assets, const Space* last, const Statistics& statistics, const NoGoods& nogoods); @@ -2348,20 +2370,19 @@ namespace Gecode { /** * \brief Hub hook for meta search engines * - * Restart-based search (RBS) calls hub() on its hub whenever an - * episode ends with a solution or at the cutoff, and when an episode - * that searches a spoke of SpokeCoverage::Partial is exhausted or - * ends without a proof (see MetaEvent). Any other episode that ends - * this way ends RBS with Search::EndReason::Exhausted or - * Search::EndReason::Incomplete instead. + * Restart-based search (RBS) calls hub() on its hub when search + * starts and whenever an episode ends with a solution, at the + * cutoff, or without a proof (see MetaEvent). An episode that + * exhausts a spoke of SpokeCoverage::Full or SpokeCoverage::Reduced + * ends RBS with Search::EndReason::Exhausted instead. * Portfolio-based search (PBS) calls hub() once, with * MetaEvent::Start, before it creates the assets. * * The hook may post constraints in the hub and sets what the engine - * does next with \a hc.decision() (see MetaDecision). If the hub - * fails, the engine ends with Search::EndReason::Exhausted whatever - * the decision: failing the hub is how a hook declares that no - * further solution exists. + * does next with \a hc.decision() (see MetaDecision for the legal + * decisions and the default). If the hub fails, the engine ends + * with Search::EndReason::Exhausted whatever the decision: failing + * the hub is how a hook declares that no further solution exists. * * In best solution search, RBS constrains the hub with each new * solution before it calls hub(), so an override cannot lose the @@ -3449,21 +3470,31 @@ namespace Gecode { return _nogoods; } + forceinline bool + HubContext::legal(MetaEvent e, MetaDecision d) { + // Only an episode that found a solution or reached the cutoff continues + return (d != MetaDecision::Continue) || + (e == MetaEvent::Solution) || (e == MetaEvent::Limit); + } forceinline - HubContext::HubContext(MetaEngine engine, MetaEvent event, + HubContext::HubContext(MetaEngine engine, MetaEvent event, MetaDecision d, unsigned long int episode, unsigned int asset, unsigned int assets, const Space* last, const Search::Statistics& statistics, const NoGoods& nogoods) : MetaContext(engine,event,episode,asset,assets,last,statistics,nogoods), - _decision(MetaDecision::Restart) {} + _decision(d) { + assert(legal(event,d)); + } forceinline MetaDecision HubContext::decision(void) const { return _decision; } forceinline void HubContext::decision(MetaDecision d) { + if (!legal(_event,d)) + throw IllegalMetaDecision("HubContext::decision"); _decision = d; } @@ -3487,12 +3518,12 @@ namespace Gecode { forceinline HubContext Search::MetaContextAccess::hub(MetaEngine engine, MetaEvent event, - unsigned long int episode, + MetaDecision d, unsigned long int episode, unsigned int asset, unsigned int assets, const Space* last, const Statistics& statistics, const NoGoods& nogoods) { - return HubContext(engine,event,episode,asset,assets,last,statistics, + return HubContext(engine,event,d,episode,asset,assets,last,statistics, nogoods); } forceinline SpokeContext diff --git a/gecode/kernel/exception.cpp b/gecode/kernel/exception.cpp index a273a04699..8dc6000879 100644 --- a/gecode/kernel/exception.cpp +++ b/gecode/kernel/exception.cpp @@ -89,6 +89,9 @@ namespace Gecode { MoreThanOneTracer::MoreThanOneTracer(const char* l) : Exception(l,"Attempt create more than one non-variable tracer") {} + IllegalMetaDecision::IllegalMetaDecision(const char* l) + : Exception(l,"Illegal decision for the event of a meta search hook") {} + } // STATISTICS: kernel-other diff --git a/gecode/kernel/exception.hpp b/gecode/kernel/exception.hpp index 3c174d33bc..5d46874730 100644 --- a/gecode/kernel/exception.hpp +++ b/gecode/kernel/exception.hpp @@ -166,6 +166,13 @@ namespace Gecode { MoreThanOneTracer(const char* l); }; + /// %Exception: illegal decision of a meta search hook (see MetaDecision) + class GECODE_KERNEL_EXPORT IllegalMetaDecision : public Exception { + public: + /// Initialize with location \a l + IllegalMetaDecision(const char* l); + }; + //@} } diff --git a/gecode/search.hh b/gecode/search.hh index 0dccb78284..cdf3c4ebfc 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1521,11 +1521,11 @@ namespace Gecode { * and * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() on its hub after solutions and at restarts, - * and spoke() on each spoke it clones from the hub. When \a E is a best - * solution engine, the engine constrains the hub by each solution - * before it calls hub(). See Space::hub() and Space::spoke() for - * details. + * The engine calls hub() on its hub when search starts and after each + * episode, and spoke() on each spoke it clones from the hub. When \a E + * is a best solution engine, the engine constrains the hub by each + * solution before it calls hub(). See Space::hub() and Space::spoke() + * for details. * * \ingroup TaskModelSearch */ @@ -1555,11 +1555,11 @@ namespace Gecode { * and * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() on its hub after solutions and at restarts, - * and spoke() on each spoke it clones from the hub. When \a E is a best - * solution engine, the engine constrains the hub by each solution - * before it calls hub(). See Space::hub() and Space::spoke() for - * details. + * The engine calls hub() on its hub when search starts and after each + * episode, and spoke() on each spoke it clones from the hub. When \a E + * is a best solution engine, the engine constrains the hub by each + * solution before it calls hub(). See Space::hub() and Space::spoke() + * for details. * * \ingroup TaskModelSearch */ diff --git a/gecode/search/pbs.hpp b/gecode/search/pbs.hpp index 7d7426d549..041bb3225d 100644 --- a/gecode/search/pbs.hpp +++ b/gecode/search/pbs.hpp @@ -152,24 +152,28 @@ namespace Gecode { namespace Search { * \brief Run hub() with MetaEvent::Start on the hub \a hub of a portfolio * of \a n assets and propagate it * - * Return whether the portfolio must be built. Otherwise the hub has - * failed and \a hub is deleted. + * Return EndReason::NotEnded if the portfolio must be built. Otherwise + * delete \a hub and return EndReason::Exhausted if the hub failed or + * EndReason::Incomplete if hub() decided to finish. */ template - bool + EndReason pbs_start(T* hub, unsigned int n, Statistics& stat) { std::unique_ptr owned(hub); Statistics start; HubContext hc = MetaContextAccess::hub(MetaEngine::Portfolio, - MetaEvent::Start,0UL,0U,n, + MetaEvent::Start, + MetaDecision::Restart,0UL,0U,n, nullptr,start,NoGoods::eng); hub->hub(hc); if (hub->status(stat) == SS_FAILED) { stat.fail++; - return false; + return EndReason::Exhausted; } + if (hc.decision() == MetaDecision::Finish) + return EndReason::Incomplete; (void) owned.release(); - return true; + return EndReason::NotEnded; } /** @@ -484,7 +488,7 @@ namespace Gecode { stat.fail++; if (!opt.clone) delete s; - e = Search::Seq::dead(opt,stat); + e = Search::Seq::dead(opt,stat,Search::EndReason::Exhausted); /* * The assets would own the cutoff, but a dead engine does not take * it. This includes the cutoff of an outer portfolio when this is @@ -501,8 +505,9 @@ namespace Gecode { opt.clone = false; bool hub_branchers = BrancherGroup::all.size(*hub) > 0U; - if (!Search::pbs_start(hub,opt.assets,stat)) { - e = Search::Seq::dead(opt,stat); + Search::EndReason r = Search::pbs_start(hub,opt.assets,stat); + if (r != Search::EndReason::NotEnded) { + e = Search::Seq::dead(opt,stat,r); Search::pbs_release_cutoff >(opt.cutoff); return; } @@ -568,7 +573,7 @@ namespace Gecode { if (!opt.clone) delete s; Search::pbscleanup(sebs); - e = Search::Seq::dead(opt,stat); + e = Search::Seq::dead(opt,stat,Search::EndReason::Exhausted); return; } @@ -578,17 +583,16 @@ namespace Gecode { opt.clone = false; bool hub_branchers = BrancherGroup::all.size(*hub) > 0U; - bool started; + Search::EndReason r; try { - started = Search::pbs_start(hub,static_cast(sebs.size()), - stat); + r = Search::pbs_start(hub,static_cast(sebs.size()),stat); } catch (...) { Search::pbscleanup(sebs); throw; } - if (!started) { + if (r != Search::EndReason::NotEnded) { Search::pbscleanup(sebs); - e = Search::Seq::dead(opt,stat); + e = Search::Seq::dead(opt,stat,r); return; } diff --git a/gecode/search/rbs.hpp b/gecode/search/rbs.hpp index f9b4f75068..2468b8fe7f 100644 --- a/gecode/search/rbs.hpp +++ b/gecode/search/rbs.hpp @@ -107,13 +107,28 @@ namespace Gecode { stat.fail++; if (!m_opt.clone) delete s; - e = Search::Seq::dead(e_opt, stat); + e = Search::Seq::dead(e_opt,stat,Search::EndReason::Exhausted); // The engine owns the cutoff, but a dead engine does not take it delete m_opt.cutoff; } else { std::unique_ptr hub(m_opt.clone ? s->clone() : s); - std::unique_ptr spoke(hub->clone()); Search::Statistics start; + HubContext hc = Search::MetaContextAccess::hub( + MetaEngine::Restart,MetaEvent::Start,MetaDecision::Restart,0UL,0U,1U, + nullptr,start,NoGoods::eng); + hub->hub(hc); + if ((hub->status(stat) == SS_FAILED) || + (hc.decision() == MetaDecision::Finish)) { + // A failed hub is a proof, finishing is not + Search::EndReason r = hub->failed() ? + Search::EndReason::Exhausted : Search::EndReason::Incomplete; + if (r == Search::EndReason::Exhausted) + stat.fail++; + e = Search::Seq::dead(e_opt,stat,r); + delete m_opt.cutoff; + return; + } + std::unique_ptr spoke(hub->clone()); SpokeContext sc = Search::MetaContextAccess::spoke( MetaEngine::Restart,MetaEvent::Start,0UL,0U,1U,nullptr,start, NoGoods::eng); diff --git a/gecode/search/seq/dead.cpp b/gecode/search/seq/dead.cpp index 550b87f350..657af57540 100644 --- a/gecode/search/seq/dead.cpp +++ b/gecode/search/seq/dead.cpp @@ -35,7 +35,7 @@ namespace Gecode { namespace Search { namespace Seq { - /// A dead engine (failed root) + /// A dead engine (failed root, or a meta engine that has finished) template class GECODE_SEARCH_EXPORT Dead : public Engine { protected: @@ -43,12 +43,14 @@ namespace Gecode { namespace Search { namespace Seq { Tracer tracer; /// Statistics Statistics stat; + /// Why next() returns no solution + EndReason reason; /// Why the last call to next() returned no solution EndReason end; public: - /// Initialize - Dead(const Options& o, const Statistics& stat0); + /// Initialize, next() returns no solution for reason \a r + Dead(const Options& o, const Statistics& stat0, EndReason r); /// Return next solution (nullptr, if none exists or search has been stopped) virtual Space* next(void); /// Return statistics @@ -60,8 +62,9 @@ namespace Gecode { namespace Search { namespace Seq { }; template - Dead::Dead(const Options& o, const Statistics& stat0) - : tracer(o.tracer), stat(stat0) , end(EndReason::NotEnded) { + Dead::Dead(const Options& o, const Statistics& stat0, + EndReason r) + : tracer(o.tracer), stat(stat0), reason(r), end(EndReason::NotEnded) { tracer.engine(SearchTracer::EngineType::AOE, 1U); tracer.worker(); } @@ -69,8 +72,7 @@ namespace Gecode { namespace Search { namespace Seq { template Space* Dead::next(void) { - // The root has failed - end = EndReason::Exhausted; + end = reason; return nullptr; } @@ -92,11 +94,11 @@ namespace Gecode { namespace Search { namespace Seq { } Engine* - dead(const Options& o, const Statistics& stat) { + dead(const Options& o, const Statistics& stat, EndReason r) { if (o.tracer) - return new Dead(o,stat); + return new Dead(o,stat,r); else - return new Dead(o,stat); + return new Dead(o,stat,r); } diff --git a/gecode/search/seq/dead.hh b/gecode/search/seq/dead.hh index 4844a59f30..4355bfbb15 100644 --- a/gecode/search/seq/dead.hh +++ b/gecode/search/seq/dead.hh @@ -38,8 +38,9 @@ namespace Gecode { namespace Search { namespace Seq { + /// Create an engine without solutions whose next() ends for reason \a r GECODE_SEARCH_EXPORT - Engine* dead(const Options& o, const Statistics& stat); + Engine* dead(const Options& o, const Statistics& stat, EndReason r); }}} diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index 17fb8d3e16..0f98498cd4 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -40,13 +40,24 @@ namespace Gecode { namespace Search { namespace Seq { + namespace { + + /// Return the default decision of hub() for event \a ev after a spoke of coverage \a c + MetaDecision + default_decision(MetaEvent ev, SpokeCoverage c) { + // A new spoke would repeat an incomplete search of a spoke that is not partial + if ((ev == MetaEvent::Incomplete) && (c != SpokeCoverage::Partial)) + return MetaDecision::Finish; + return MetaDecision::Restart; + } + + } + bool RestartStop::stop(const Statistics& s, const Options& o) { Support::Lock lock(m); // Stop if the fail limit for the engine says so if (s.fail > l) { - if (!e_stopped) - m_stat.restart++; e_stopped = true; return true; } @@ -82,33 +93,42 @@ namespace Gecode { namespace Search { namespace Seq { hub->constrain(*last); Search::Statistics episode_stat = e->statistics(); NoGoods& ng = hub_nogoods(); - HubContext hc = MetaContextAccess::hub(MetaEngine::Restart,ev,episode, - 0U,1U,last,episode_stat,ng); + HubContext hc = MetaContextAccess::hub(MetaEngine::Restart,ev, + default_decision(ev,coverage), + episode,0U,1U,last,episode_stat, + ng); hub->hub(hc); stop->nogood(ng.ng()); - // Only an episode that found a solution can continue - bool cont = (ev == MetaEvent::Solution) && - (hc.decision() == MetaDecision::Continue); - // Any other episode ends with a restart that takes the next cutoff - if (ev != MetaEvent::Solution) - stop->limit(e->statistics(),++(*co)); + MetaDecision d = hc.decision(); if (stop->status(hub) == SS_FAILED) { // A failed hub proves that no further solution exists - if (ev == MetaEvent::Solution) - stop->update(e->statistics()); + stop->update(e->statistics()); delete hub; hub = nullptr; e->reset(nullptr); end = EndReason::Exhausted; return false; } - if (cont) + switch (d) { + case MetaDecision::Finish: + end = EndReason::Incomplete; + return false; + case MetaDecision::Continue: + // After a limit, the episode continues with the next cutoff as budget + if (ev == MetaEvent::Limit) + stop->extend(e->statistics().fail + ++(*co)); return true; - if (ev == MetaEvent::Solution) { - // A restart after a solution keeps the cutoff - stop->update(e->statistics()); - stop->restart(); + case MetaDecision::Restart: + break; + default: + GECODE_NEVER; } + stop->restart(); + // A restart after a solution keeps the cutoff + if (ev == MetaEvent::Solution) + stop->update(e->statistics()); + else + stop->limit(e->statistics(),++(*co)); Space* spoke = hub; hub = hub->clone(); episode++; @@ -122,11 +142,9 @@ namespace Gecode { namespace Search { namespace Seq { Space* RBS::next(void) { - // A failed hub proves that no further solution exists - if (hub == nullptr) { - end = EndReason::Exhausted; + // A proof or a decision to finish ends the search + if ((end == EndReason::Exhausted) || (end == EndReason::Incomplete)) return nullptr; - } if (solution) { solution = false; if (!hub_event(MetaEvent::Solution)) @@ -150,7 +168,6 @@ namespace Gecode { namespace Search { namespace Seq { end = EndReason::Limit; return nullptr; } - // The stop object has counted the restart ev = MetaEvent::Limit; break; case EndReason::Exhausted: @@ -162,28 +179,21 @@ namespace Gecode { namespace Search { namespace Seq { ev = MetaEvent::Exhausted; break; case EndReason::Incomplete: - if (coverage != SpokeCoverage::Partial) { - // A new spoke would repeat the same incomplete search - end = EndReason::Incomplete; - return nullptr; - } ev = MetaEvent::Incomplete; break; default: GECODE_NEVER; return nullptr; } - if (ev != MetaEvent::Limit) { - /* - * The engine might not have checked its stop object, for example - * when the spoke failed at the root or a parallel engine had no - * work. Without this check, the restarts might never stop. - */ - if (stop->meta_stop(e->statistics(),m_opt)) { - end = EndReason::Limit; - return nullptr; - } - stop->restart(); + /* + * The engine might not have checked its stop object, for example + * when the spoke failed at the root or a parallel engine had no + * work. Without this check, the restarts might never stop. + */ + if ((ev != MetaEvent::Limit) && + stop->meta_stop(e->statistics(),m_opt)) { + end = EndReason::Limit; + return nullptr; } if (!hub_event(ev)) return nullptr; diff --git a/gecode/search/seq/rbs.hh b/gecode/search/seq/rbs.hh index 4daa27e18a..4ea474a991 100755 --- a/gecode/search/seq/rbs.hh +++ b/gecode/search/seq/rbs.hh @@ -74,6 +74,8 @@ namespace Gecode { namespace Search { namespace Seq { SpaceStatus status(Space* s); /// Add statistics \a s and set the limit for the engine to \a l fails void limit(const Statistics& s, unsigned long long int l); + /// Set the limit for the engine, which continues its search, to \a l fails + void extend(unsigned long long int l); /// Update statistics void update(const Search::Statistics& s); /// Return whether the engine has been stopped diff --git a/gecode/search/seq/rbs.hpp b/gecode/search/seq/rbs.hpp index 854d26e9b4..a6d2464433 100755 --- a/gecode/search/seq/rbs.hpp +++ b/gecode/search/seq/rbs.hpp @@ -68,6 +68,13 @@ namespace Gecode { namespace Search { namespace Seq { e_stopped = false; } + forceinline void + RestartStop::extend(unsigned long long int l0) { + Support::Lock lock(m); + l = l0; + e_stopped = false; + } + forceinline void RestartStop::update(const Search::Statistics& s) { Support::Lock lock(m); diff --git a/test/search.cpp b/test/search.cpp index cb251050c5..b34b4d89f5 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -984,20 +984,20 @@ namespace Test { HubSpokeDispatchSpace* second = search.next(); if (!fail_solution_spoke) { const bool restart = solution_decision == MetaDecision::Restart; - ok = ok && (second != nullptr) && holds(state.hub_calls, 1U) && + ok = ok && (second != nullptr) && holds(state.hub_calls, 2U) && holds(state.spoke_calls, restart ? 2U : 1U) && - holds(state.hub_events, solution) && + holds(state.hub_events, start | solution) && holds(state.spoke_events, start | (restart ? solution : 0U)); } else if (solution_spoke_coverage != SpokeCoverage::Partial) { // Exhausting a spoke that is not partial is a proof ok = ok && (second == nullptr) && (search.end_reason() == EndReason::Exhausted) && - holds(state.hub_calls, 1U) && holds(state.spoke_calls, 2U) && - holds(state.hub_events, solution) && + holds(state.hub_calls, 2U) && holds(state.spoke_calls, 2U) && + holds(state.hub_events, start | solution) && holds(state.spoke_events, start | solution); } else { - ok = ok && (second != nullptr) && holds(state.hub_calls, 2U) && holds(state.spoke_calls, 3U) && - holds(state.hub_events, solution | exhausted) && + ok = ok && (second != nullptr) && holds(state.hub_calls, 3U) && holds(state.spoke_calls, 3U) && + holds(state.hub_events, start | solution | exhausted) && holds(state.spoke_events, start | solution | exhausted); } delete second; @@ -1061,9 +1061,10 @@ namespace Test { delete m; HubSpokeDispatchSpace* solution = search.next(); - bool ok = (solution != nullptr) && solution->assigned() && holds(state.hub_calls, 1U) && - holds(state.spoke_calls, 2U) && holds(state.hub_events, event_bit(MetaEvent::Limit)) && - holds(state.spoke_events, event_bit(MetaEvent::Start) | event_bit(MetaEvent::Limit)); + const unsigned int events = event_bit(MetaEvent::Start) | event_bit(MetaEvent::Limit); + bool ok = (solution != nullptr) && solution->assigned() && holds(state.hub_calls, 2U) && + holds(state.spoke_calls, 2U) && holds(state.hub_events, events) && + holds(state.spoke_events, events); delete solution; return ok; } @@ -1232,7 +1233,7 @@ namespace Test { run(void) override { switch (scenario) { case Scenario::RbsHubOnly: - return rbs_dispatch(1, 0); + return rbs_dispatch(2, 0); case Scenario::RbsSpokeOnly: return rbs_dispatch(0, 2); case Scenario::RbsHubContinue: @@ -3064,7 +3065,7 @@ namespace Test { Gecode::Search::Statistics s = rbs.statistics(); // The failures of the last spoke search are counted once if ((rbs.end_reason() != EndReason::Exhausted) || - (s.restart != 1U) || (s.fail < 2U) || + (s.restart != 0U) || (s.fail < 2U) || ((t == 1U) && (s.fail != 2U))) return false; if ((rbs.next() != nullptr) || @@ -3267,6 +3268,72 @@ namespace Test { LDSIncomplete lds_incomplete; + /// Space without solutions recording the default decisions after incomplete episodes + class IncompleteEpisodes : public NoSolution { + public: + /// Coverage that spoke() declares + Gecode::SpokeCoverage coverage; + /// Default decisions of hub() after an incomplete episode + std::vector* defaults; + IncompleteEpisodes(Gecode::SpokeCoverage c, + std::vector& d) + : coverage(c), defaults(&d) {} + IncompleteEpisodes(IncompleteEpisodes& s) + : NoSolution(s), coverage(s.coverage), defaults(s.defaults) {} + Gecode::Space* copy(void) override { + return new IncompleteEpisodes(*this); + } + void hub(Gecode::HubContext& hc) override { + if (hc.event() == Gecode::MetaEvent::Incomplete) { + defaults->push_back(hc.decision()); + // Finish after the second incomplete episode at the latest + if (defaults->size() == 2U) + hc.decision(Gecode::MetaDecision::Finish); + } + NoSolution::hub(hc); + } + void spoke(Gecode::SpokeContext& sc) override { + sc.coverage(coverage); + } + }; + + /// RBS finishes after an incomplete episode unless its spoke is partial + class RBSIncompleteDefault : public Base { + /// Return the default decisions when spokes of coverage \a c end incomplete + static std::vector + defaults(Gecode::SpokeCoverage c) { + std::vector d; + IncompleteEpisodes root(c,d); + Gecode::Search::Options o; + o.d_l = 1; + o.cutoff = Gecode::Search::Cutoff::constant(1000); + Gecode::RBS rbs(&root,o); + for (int i=0; i<2; i++) + if (IncompleteEpisodes* s = rbs.next()) { + delete s; + d.clear(); + } else if (rbs.end_reason() != EndReason::Incomplete) { + d.clear(); + } + return d; + } + public: + RBSIncompleteDefault(void) : Base("Search::RBS::IncompleteDefault") {} + bool run(void) override { + using Gecode::MetaDecision; + using Gecode::SpokeCoverage; + using Decisions = std::vector; + return (defaults(SpokeCoverage::Full) == + Decisions{MetaDecision::Finish}) && + (defaults(SpokeCoverage::Reduced) == + Decisions{MetaDecision::Finish}) && + (defaults(SpokeCoverage::Partial) == + Decisions{MetaDecision::Restart,MetaDecision::Restart}); + } + }; + + RBSIncompleteDefault rbs_incomplete_default; + /// Space for relaxing class RelaxSpace : public Gecode::Space { public: @@ -3700,9 +3767,16 @@ namespace Test { /// Hook behaviour of ProtocolSpace enum class Protocol { - Default, ///< Default hooks - EmptyHub, ///< hub() does nothing - BoundInHub, ///< hub() posts c <= 1 at Start and keeps the branchers + Default, ///< Default hooks + ContinueAtStart, ///< hub() continues at Start, which is illegal + FinishAtStart, ///< hub() finishes at Start + FinishAtLimit, ///< hub() finishes at Limit + FailAtStart, ///< hub() fails at Start + FailAtSolution, ///< hub() fails at Solution + ContinueAtLimit, ///< hub() continues at Limit + EmptyHub, ///< hub() does nothing + BoundInHub, ///< hub() posts c <= 1 at Start and keeps the branchers + Alternate, ///< Episodes alternate between a solution and the cutoff }; /// Calls of the hooks of ProtocolSpace @@ -3761,6 +3835,36 @@ namespace Test { void hub(HubContext& hc) override { log->hub.emplace_back(hc.event(),hc.episode()); switch (protocol) { + case Protocol::ContinueAtStart: + if (hc.event() == MetaEvent::Start) + hc.decision(MetaDecision::Continue); + break; + case Protocol::FinishAtStart: + if (hc.event() == MetaEvent::Start) { + hc.decision(MetaDecision::Finish); + return; + } + break; + case Protocol::FinishAtLimit: + if (hc.event() == MetaEvent::Limit) + hc.decision(MetaDecision::Finish); + break; + case Protocol::FailAtStart: + if (hc.event() == MetaEvent::Start) { + fail(); + return; + } + break; + case Protocol::FailAtSolution: + if (hc.event() == MetaEvent::Solution) { + fail(); + return; + } + break; + case Protocol::ContinueAtLimit: + if (hc.event() == MetaEvent::Limit) + hc.decision(MetaDecision::Continue); + break; case Protocol::EmptyHub: return; case Protocol::BoundInHub: @@ -3770,12 +3874,19 @@ namespace Test { } break; case Protocol::Default: + case Protocol::Alternate: break; } IntMinimizeSpace::hub(hc); } void spoke(SpokeContext& sc) override { log->spoke.emplace_back(sc.event(),sc.episode()); + if ((protocol == Protocol::Alternate) && + (sc.engine() == MetaEngine::Restart)) { + // Odd episodes search only the part without solutions + rel(*this,p,IRT_EQ,((sc.episode() % 2U) == 1U) ? 1 : 0); + sc.coverage(SpokeCoverage::Partial); + } } }; @@ -3784,8 +3895,16 @@ namespace Test { public: /// Scenario enum class Scenario { + DecisionLegality, + IllegalDecisionInEngine, + FinishAtStart, + FinishAtLimit, + FailAtStart, + FailAtSolution, + ContinueAtLimit, EngineConstrainsHub, PortfolioHubConstraint, + Episodes, }; protected: /// Scenario under test @@ -3797,6 +3916,167 @@ namespace Test { o.cutoff = Gecode::Search::Cutoff::constant(c); return o; } + /// Return whether engine \a e has no further solution and ends with \a r + template + static bool ends(Engine& e, EndReason r) { + for (int i=0; i<2; i++) { + if (ProtocolSpace* s = e.next()) { + delete s; + return false; + } + if (e.end_reason() != r) + return false; + } + return true; + } + /// Return whether \a d is legal after event \a e + static bool legal(MetaEvent e, MetaDecision d) { + return (d != MetaDecision::Continue) || + (e == MetaEvent::Solution) || (e == MetaEvent::Limit); + } + /// Check the legality of each decision for each event + static bool decision_legality(void) { + const Gecode::Search::Statistics stat; + for (MetaEvent e : {MetaEvent::Start,MetaEvent::Solution, + MetaEvent::Exhausted,MetaEvent::Incomplete, + MetaEvent::Limit}) + for (MetaDecision d : {MetaDecision::Restart,MetaDecision::Continue, + MetaDecision::Finish}) { + HubContext hc = Gecode::Search::MetaContextAccess::hub + (MetaEngine::Restart,e,MetaDecision::Restart,0,0,1,nullptr, + stat,NoGoods::eng); + if (hc.decision() != MetaDecision::Restart) + return false; + bool thrown = false; + try { + hc.decision(d); + } catch (const IllegalMetaDecision&) { + thrown = true; + } + if ((thrown == legal(e,d)) || + (hc.decision() != (thrown ? MetaDecision::Restart : d))) + return false; + } + // The engine sets the default decision + HubContext fc = Gecode::Search::MetaContextAccess::hub + (MetaEngine::Restart,MetaEvent::Incomplete,MetaDecision::Finish, + 0,0,1,nullptr,stat,NoGoods::eng); + if (fc.decision() != MetaDecision::Finish) + return false; + SpokeContext sc = Gecode::Search::MetaContextAccess::spoke + (MetaEngine::Restart,MetaEvent::Start,0,0,1,nullptr,stat, + NoGoods::eng); + if (sc.coverage() != SpokeCoverage::Full) + return false; + sc.coverage(SpokeCoverage::Partial); + sc.coverage(SpokeCoverage::Reduced); + return sc.coverage() == SpokeCoverage::Reduced; + } + /// Check that an illegal decision throws from the engine + static bool illegal_decision_in_engine(void) { + ProtocolLog log; + ProtocolSpace* m = new ProtocolSpace(Protocol::ContinueAtStart,log); + Gecode::Search::Options o = rbs_options(10); + bool thrown = false; + try { + Gecode::RBS rbs(m,o); + } catch (const IllegalMetaDecision&) { + // The engine owns the cutoff only once it is constructed + delete o.cutoff; + thrown = true; + } + delete m; + return thrown && log.spoke.empty() && (log.live == 0); + } + /// Check that RBS and PBS end with \a r when hub() at Start follows \a pr + static bool ends_at_start(Protocol pr, EndReason r) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(pr,log); + Gecode::RBS rbs(m,rbs_options(10)); + delete m; + if (!ends(rbs,r)) + return false; + } + for (unsigned int t : {1U,2U}) { + ProtocolSpace* m = new ProtocolSpace(pr,log); + Gecode::Search::Options o; + o.assets = 2; + o.threads = t; + Gecode::PBS pbs(m,o); + delete m; + if (!ends(pbs,r)) + return false; + } + { + ProtocolSpace* m = new ProtocolSpace(pr,log); + Gecode::Search::Options o; + o.threads = 1; + SEBs assets(2); + for (int i=0; i<2; i++) + assets[i] = Gecode::dfs(o); + Gecode::PBS pbs(m,assets,o); + delete m; + if (!ends(pbs,r)) + return false; + } + return log.spoke.empty() && (log.hub.size() == 4U) && (log.live == 0); + } + /// Check that Finish at Limit ends RBS without a proof + static bool finish_at_limit(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::FinishAtLimit,log); + Gecode::RBS rbs(m,rbs_options(1)); + delete m; + if (!ends(rbs,EndReason::Incomplete) || + (rbs.statistics().restart != 0U)) + return false; + } + using Call = std::pair; + return (log.hub == std::vector{{MetaEvent::Start,0}, + {MetaEvent::Limit,0}}) && + (log.spoke == std::vector{{MetaEvent::Start,0}}) && + (log.live == 0); + } + /// Check that a hub failing after a solution proves exhaustion + static bool fail_at_solution(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::FailAtSolution,log); + Gecode::RBS rbs(m,rbs_options(100)); + delete m; + ProtocolSpace* s = rbs.next(); + if (s == nullptr) + return false; + delete s; + if (!ends(rbs,EndReason::Exhausted)) + return false; + } + return (log.spoke.size() == 1U) && (log.live == 0); + } + /// Check that Continue at Limit resumes the same spoke + static bool continue_at_limit(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::ContinueAtLimit,log); + Gecode::RBS rbs(m,rbs_options(1)); + delete m; + ProtocolSpace* s = rbs.next(); + if (s == nullptr) + return false; + const bool assigned = s->p.assigned() && (s->p.val() == 0); + delete s; + if (!assigned || (rbs.statistics().restart != 0U)) + return false; + } + if ((log.spoke.size() != 1U) || (log.hub.size() < 3U)) + return false; + for (std::size_t i=1; i constrains the hub when hub() does nothing static bool engine_constrains_hub(void) { ProtocolLog log; @@ -3850,16 +4130,61 @@ namespace Test { } return log.live == 0; } + /// Check episode numbering across solution and limit restarts + static bool episodes(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::Alternate,log); + Gecode::RBS rbs(m,rbs_options(2)); + delete m; + for (int i=0; i<3; i++) { + ProtocolSpace* s = rbs.next(); + if (s == nullptr) + return false; + delete s; + } + if (rbs.statistics().restart != 4U) + return false; + } + using Call = std::pair; + const std::vector hub{{MetaEvent::Start,0}, + {MetaEvent::Solution,0}, + {MetaEvent::Limit,1}, + {MetaEvent::Solution,2}, + {MetaEvent::Limit,3}}; + const std::vector spoke{{MetaEvent::Start,0}, + {MetaEvent::Solution,1}, + {MetaEvent::Limit,2}, + {MetaEvent::Solution,3}, + {MetaEvent::Limit,4}}; + return (log.hub == hub) && (log.spoke == spoke) && (log.live == 0); + } public: /// Initialize scenario \a s with name \a n MetaProtocol(const std::string& n, Scenario s) : Base("Search::Meta::"+n), scenario(s) {} bool run(void) override { switch (scenario) { + case Scenario::DecisionLegality: + return decision_legality(); + case Scenario::IllegalDecisionInEngine: + return illegal_decision_in_engine(); + case Scenario::FinishAtStart: + return ends_at_start(Protocol::FinishAtStart,EndReason::Incomplete); + case Scenario::FinishAtLimit: + return finish_at_limit(); + case Scenario::FailAtStart: + return ends_at_start(Protocol::FailAtStart,EndReason::Exhausted); + case Scenario::FailAtSolution: + return fail_at_solution(); + case Scenario::ContinueAtLimit: + return continue_at_limit(); case Scenario::EngineConstrainsHub: return engine_constrains_hub(); case Scenario::PortfolioHubConstraint: return portfolio_hub_constraint(); + case Scenario::Episodes: + return episodes(); default: GECODE_NEVER; } @@ -3867,10 +4192,26 @@ namespace Test { } }; + MetaProtocol meta_decision_legality + ("DecisionLegality",MetaProtocol::Scenario::DecisionLegality); + MetaProtocol meta_illegal_decision_in_engine + ("IllegalDecisionInEngine", + MetaProtocol::Scenario::IllegalDecisionInEngine); + MetaProtocol meta_finish_at_start + ("FinishAtStart",MetaProtocol::Scenario::FinishAtStart); + MetaProtocol meta_finish_at_limit + ("FinishAtLimit",MetaProtocol::Scenario::FinishAtLimit); + MetaProtocol meta_fail_at_start + ("FailAtStart",MetaProtocol::Scenario::FailAtStart); + MetaProtocol meta_fail_at_solution + ("FailAtSolution",MetaProtocol::Scenario::FailAtSolution); + MetaProtocol meta_continue_at_limit + ("ContinueAtLimit",MetaProtocol::Scenario::ContinueAtLimit); MetaProtocol meta_engine_constrains_hub ("EngineConstrainsHub",MetaProtocol::Scenario::EngineConstrainsHub); MetaProtocol meta_portfolio_hub_constraint ("PortfolioHubConstraint",MetaProtocol::Scenario::PortfolioHubConstraint); + MetaProtocol meta_episodes("Episodes",MetaProtocol::Scenario::Episodes); /** * \brief Constant cutoff counting its deletions From 9840098c40acb5145c0b7669516d795ab20169f4 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 21:15:37 +0100 Subject: [PATCH 13/37] Keep hub branchers from taking the ids of spoke branchers A brancher that spoke() posts gets the next brancher id of the spoke. The hub, from which the spoke was cloned, still has the same counter, so a brancher that hub() posts later got the same id. Restart-based search then posted the no-goods of the spoke, which refer to the spoke's brancher by its id, for the hub's brancher: the no-goods could prune the wrong variables and lose solutions, or reach a brancher of another type. The engine now calls Space::reserve_brancher_ids() on the hub after each spoke(), so the hub's later branchers get fresh ids and no-goods for the spoke's branchers find no brancher in the hub. Branchers that other branchers post during the search of a spoke are not covered; the hub() documentation says so. --- changelog.in | 11 +++++++ gecode/kernel/core.hpp | 26 +++++++++++++++ gecode/search/rbs.hpp | 1 + gecode/search/seq/rbs.cpp | 1 + test/search.cpp | 66 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 105 insertions(+) diff --git a/changelog.in b/changelog.in index 57964abf3f..01e7aeffd5 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,17 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Do not let a brancher that hub() posts take the identity of a brancher that +spoke() posted earlier. +[MORE] +Restart-based search then posted the no-goods of that spoke for the wrong +brancher, which could lose solutions. + [ENTRY] Module: search What: change diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 3dc0bd1519..a640a69fc3 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -2392,6 +2392,14 @@ namespace Gecode { * removes all branchers, so spoke() must post the branching of each * asset. * + * No-goods refer to the branchers that created their choices. RBS + * keeps a brancher that hub() posts from taking the identity of a + * brancher that spoke() posted, so the no-goods of a spoke are never + * posted for the wrong brancher. This does not cover branchers that + * other branchers post while a spoke is searched: if there are such + * branchers and the spoke has SpokeCoverage::Full, hub() must not + * post branchers. + * * \ingroup TaskModelScript */ GECODE_KERNEL_EXPORT @@ -2443,6 +2451,17 @@ namespace Gecode { SpaceStatus status(StatusStatistics& stat); /// Query space status without collecting statistics SpaceStatus status(void); + /** + * \brief Reserve in this space the brancher ids that clone \a s uses + * + * A meta search engine calls this on its hub after spoke() has run + * on the clone \a s. A brancher that hub() posts later then never + * gets the id of a brancher that spoke() posted, so a no-good + * recorded in the spoke cannot reach the wrong brancher of the hub. + * + * \ingroup TaskSearch + */ + void reserve_brancher_ids(const Space& s); /** * \brief Create new choice for current brancher @@ -3650,6 +3669,13 @@ namespace Gecode { return status(stat); } + forceinline void + Space::reserve_brancher_ids(const Space& s) { + unsigned int n = s.pc.p.bid_sc >> sc_bits; + if (n > (pc.p.bid_sc >> sc_bits)) + pc.p.bid_sc = (n << sc_bits) | (pc.p.bid_sc & ((1U << sc_bits) - 1U)); + } + forceinline Space* Space::clone(void) const { CloneStatistics stat; diff --git a/gecode/search/rbs.hpp b/gecode/search/rbs.hpp index 2468b8fe7f..6352e9328d 100644 --- a/gecode/search/rbs.hpp +++ b/gecode/search/rbs.hpp @@ -133,6 +133,7 @@ namespace Gecode { MetaEngine::Restart,MetaEvent::Start,0UL,0U,1U,nullptr,start, NoGoods::eng); spoke->spoke(sc); + hub->reserve_brancher_ids(*spoke); std::unique_ptr leaf( Search::build(spoke.get(),e_opt)); e = Search::Seq::rbsengine(hub.get(),stop.get(),leaf.get(), diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index 0f98498cd4..ecae1b136e 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -135,6 +135,7 @@ namespace Gecode { namespace Search { namespace Seq { SpokeContext sc = MetaContextAccess::spoke(MetaEngine::Restart,ev,episode, 0U,1U,last,episode_stat,ng); spoke->spoke(sc); + hub->reserve_brancher_ids(*spoke); coverage = sc.coverage(); e->reset(spoke); return true; diff --git a/test/search.cpp b/test/search.cpp index b34b4d89f5..a9ae826719 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -3005,6 +3005,72 @@ namespace Test { RBSPartialNoGoods rbs_partial_nogoods; + /// Space whose hub posts a brancher after a spoke posted one + class LateHubBrancher : public Gecode::Space { + public: + /// Variables branched on by the spokes + Gecode::IntVarArray y; + /// Variables branched on by the hub after the first episode + Gecode::IntVarArray z; + /// Whether the hub branches on z + bool z_branching; + LateHubBrancher(void) + : y(*this,5,0,2), z(*this,2,0,1), z_branching(false) { + // For y0 = 0 the other y must be distinct, which is impossible + Gecode::BoolVar b = Gecode::expr(*this,y[0] == 0); + for (int i=1; i rbs(m,o); + delete m; + // A no-good taken for one on z would rule out z = (0,0) + LateHubBrancher* s = rbs.next(); + const bool ok = (s != nullptr) && + (s->z[0].val() == 0) && (s->z[1].val() == 0); + delete s; + return ok; + } + }; + + RBSLateHubBrancher rbs_late_hub_brancher; + /// Space without solutions whose search tree has several failures class NoSolution : public Gecode::IntMinimizeSpace { public: From 2af7674c50b23413415be4f1f4de480a8b6c4fed Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 21:16:18 +0100 Subject: [PATCH 14/37] Delete the spoke when spoke() throws at a restart Restart-based search took the old hub as the spoke and called spoke() on it before handing it to the engine. An exception from spoke() or from reserving the brancher ids leaked the spoke. Hold it in a unique_ptr until the engine takes it. --- changelog.in | 8 ++++++ gecode/search/seq/rbs.cpp | 10 +++++--- test/search.cpp | 54 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 3 deletions(-) diff --git a/changelog.in b/changelog.in index 01e7aeffd5..07fc7b4e34 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,14 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Delete the spoke of restart-based search when spoke() throws an exception at +a restart. + [ENTRY] Module: search What: bug diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index ecae1b136e..cadbb1fecf 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -38,6 +38,8 @@ #include +#include + namespace Gecode { namespace Search { namespace Seq { namespace { @@ -129,15 +131,17 @@ namespace Gecode { namespace Search { namespace Seq { stop->update(e->statistics()); else stop->limit(e->statistics(),++(*co)); - Space* spoke = hub; - hub = hub->clone(); + // The old hub becomes the spoke, which is deleted if spoke() throws + std::unique_ptr next_hub(hub->clone()); + std::unique_ptr spoke(hub); + hub = next_hub.release(); episode++; SpokeContext sc = MetaContextAccess::spoke(MetaEngine::Restart,ev,episode, 0U,1U,last,episode_stat,ng); spoke->spoke(sc); hub->reserve_brancher_ids(*spoke); coverage = sc.coverage(); - e->reset(spoke); + e->reset(spoke.release()); return true; } diff --git a/test/search.cpp b/test/search.cpp index a9ae826719..6726f8712c 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -50,6 +50,7 @@ #include #include #include +#include #include #include #include @@ -3248,6 +3249,59 @@ namespace Test { RBSFailedFirstSpoke rbs_failed_first_spoke; + /// Space without solutions whose spoke() throws after the first episode + class ThrowingSpoke : public NoSolution { + public: + /// Number of spaces alive, shared with the workers of a parallel engine + std::atomic* live; + ThrowingSpoke(std::atomic& l) : live(&l) { + (*live)++; + } + ThrowingSpoke(ThrowingSpoke& s) : NoSolution(s), live(s.live) { + (*live)++; + } + ~ThrowingSpoke(void) override { + (*live)--; + } + Gecode::Space* copy(void) override { + return new ThrowingSpoke(*this); + } + void spoke(Gecode::SpokeContext& sc) override { + if (sc.episode() == 1) + throw std::runtime_error("spoke"); + } + }; + + /// RBS deletes the spoke when spoke() throws at a restart + class RBSSpokeException : public Base { + public: + RBSSpokeException(void) : Base("Search::RBS::SpokeException") {} + bool run(void) override { + for (unsigned int t : {1U,2U}) { + std::atomic live{0}; + bool thrown = false; + { + ThrowingSpoke root(live); + Gecode::Search::Options o; + o.threads = t; + o.cutoff = Gecode::Search::Cutoff::constant(1); + Gecode::RBS rbs(&root,o); + try { + if (ThrowingSpoke* s = rbs.next()) + delete s; + } catch (const std::runtime_error&) { + thrown = true; + } + } + if (!thrown || (live != 0)) + return false; + } + return true; + } + }; + + RBSSpokeException rbs_spoke_exception; + /// Stop after a number of failures, or after many checks as a safeguard class FailureLimit : public Gecode::Search::Stop { public: From ee6cba4b7b9d256ff372c432350a8370ba343223 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 21:17:43 +0100 Subject: [PATCH 15/37] Test an exception from an asset of portfolio search An exception that a hook throws in an asset, such as IllegalMetaDecision from the hub of a restart-based asset, must not leave the thread of a parallel asset. Parallel portfolio search already catches it, stops the other assets, and rethrows it from next(). Check this for sequential and parallel portfolios. --- test/search.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/test/search.cpp b/test/search.cpp index 6726f8712c..b449eecf9c 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -3793,6 +3793,53 @@ namespace Test { PBSParkedAsset pbs_parked_asset; + /// Space without solutions whose hub continues after a partial spoke is exhausted, which is illegal + class IllegalContinue : public NoSolution { + public: + IllegalContinue(void) = default; + IllegalContinue(IllegalContinue& s) : NoSolution(s) {} + Gecode::Space* copy(void) override { + return new IllegalContinue(*this); + } + void hub(Gecode::HubContext& hc) override { + if (hc.event() == Gecode::MetaEvent::Exhausted) + hc.decision(Gecode::MetaDecision::Continue); + NoSolution::hub(hc); + } + void spoke(Gecode::SpokeContext& sc) override { + if (sc.engine() == Gecode::MetaEngine::Restart) + sc.coverage(Gecode::SpokeCoverage::Partial); + } + }; + + /// An exception thrown in an asset of a portfolio is rethrown by next() + class PBSAssetException : public Base { + public: + PBSAssetException(void) : Base("Search::PBS::AssetException") {} + bool run(void) override { + for (unsigned int t : {1U,2U,4U}) { + IllegalContinue root; + Gecode::Search::Options o; + o.assets = 2; + o.threads = t; + o.cutoff = Gecode::Search::Cutoff::constant(1000); + Gecode::PBS pbs(&root,o); + bool thrown = false; + try { + if (IllegalContinue* s = pbs.next()) + delete s; + } catch (const Gecode::IllegalMetaDecision&) { + thrown = true; + } + if (!thrown) + return false; + } + return true; + } + }; + + PBSAssetException pbs_asset_exception; + /// A copy of a cutoff generator continues its sequence independently class CutoffCopy : public Base { /// Check that a copy of \a c continues as \a c, then delete \a c From 035f64650d4042e18e96098891c574f7a9ad69fb Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Thu, 19 Nov 2026 21:18:18 +0100 Subject: [PATCH 16/37] Advance the repeated generator of Cutoff::repeat() CutoffRepeat read the current value of the generator it repeats without advancing it, so after the first value it repeated the same value forever. --- changelog.in | 11 +++++++++++ gecode/search/cutoff.cpp | 2 ++ test/search.cpp | 27 +++++++++++++++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/changelog.in b/changelog.in index 07fc7b4e34..8ef8c34b2a 100755 --- a/changelog.in +++ b/changelog.in @@ -75,6 +75,17 @@ Date: unreleased [DESCRIPTION] This is the development changelog for the next Gecode release. +[ENTRY] +Module: search +What: bug +Rank: minor +[DESCRIPTION] +Advance the generator that a cutoff generator from Cutoff::repeat() +repeats. +[MORE] +It read the current value of that generator without advancing it, so after +the first value it repeated the same value forever. + [ENTRY] Module: search What: bug diff --git a/gecode/search/cutoff.cpp b/gecode/search/cutoff.cpp index be173d5943..b9051d87c7 100755 --- a/gecode/search/cutoff.cpp +++ b/gecode/search/cutoff.cpp @@ -189,6 +189,8 @@ namespace Gecode { namespace Search { CutoffRepeat::operator ++(void) { i++; if (i == n) { + // Read the current value, which ++ need not return for all generators + (void) ++(*c); cutoff = (*c)(); i = 0; } diff --git a/test/search.cpp b/test/search.cpp index b449eecf9c..0ee71dd0c0 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -3907,6 +3907,33 @@ namespace Test { CutoffRandomCopy cutoff_random_copy; + /// A repeating cutoff generator advances the generator it repeats + class CutoffRepeat : public Base { + public: + CutoffRepeat(void) : Base("Search::Cutoff::Repeat") {} + bool run(void) override { + std::unique_ptr c + (Gecode::Search::Cutoff::repeat(Gecode::Search::Cutoff::linear(4),3)); + std::vector v{(*c)()}; + for (int i=0; i<6; i++) + v.push_back(++(*c)); + if (v != std::vector{4,4,4,8,8,8,12}) + return false; + // An appended generator returns the value of its first generator + // from ++ when it switches to its second one + std::unique_ptr a + (Gecode::Search::Cutoff::repeat + (Gecode::Search::Cutoff::append(Gecode::Search::Cutoff::linear(10),1, + Gecode::Search::Cutoff::constant(100)),2)); + std::vector w{(*a)()}; + for (int i=0; i<3; i++) + w.push_back(++(*a)); + return w == std::vector{10,10,100,100}; + } + }; + + CutoffRepeat cutoff_repeat; + /// Each restart-based asset of a portfolio owns a copy of the cutoff class PBSRestartCutoff : public Base { template class Engine> From 4595b127a6c51c7730f482c837f912f8be0d2bd3 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 24 Nov 2026 21:15:55 +0100 Subject: [PATCH 17/37] Keep the restart budget of RBS within each worker and episode A Continue decision extended the failure limit by adding the next cutoff to the failures of all workers, while the limit is checked against the failures of each worker. The sum could also wrap around and leave no budget. The extension now counts from the worker that the limit stopped and saturates. A restart after a solution kept a limit extended by Continue; it now starts the episode with the last cutoff. --- gecode/search/seq/rbs.cpp | 8 ++-- gecode/search/seq/rbs.hh | 22 +++++++++-- gecode/search/seq/rbs.hpp | 22 ++++++++--- test/search.cpp | 77 ++++++++++++++++++++++++++++++++++++++- 4 files changed, 116 insertions(+), 13 deletions(-) diff --git a/gecode/search/seq/rbs.cpp b/gecode/search/seq/rbs.cpp index cadbb1fecf..c08a9cf10c 100755 --- a/gecode/search/seq/rbs.cpp +++ b/gecode/search/seq/rbs.cpp @@ -38,6 +38,7 @@ #include +#include #include namespace Gecode { namespace Search { namespace Seq { @@ -61,6 +62,7 @@ namespace Gecode { namespace Search { namespace Seq { // Stop if the fail limit for the engine says so if (s.fail > l) { e_stopped = true; + e_fail = std::max(e_fail,s.fail); return true; } // Stop if the stop object for the meta engine says so @@ -118,7 +120,7 @@ namespace Gecode { namespace Search { namespace Seq { case MetaDecision::Continue: // After a limit, the episode continues with the next cutoff as budget if (ev == MetaEvent::Limit) - stop->extend(e->statistics().fail + ++(*co)); + stop->extend(++(*co)); return true; case MetaDecision::Restart: break; @@ -126,9 +128,9 @@ namespace Gecode { namespace Search { namespace Seq { GECODE_NEVER; } stop->restart(); - // A restart after a solution keeps the cutoff + // A restart after a solution keeps the cutoff, not an extended limit if (ev == MetaEvent::Solution) - stop->update(e->statistics()); + stop->renew(e->statistics()); else stop->limit(e->statistics(),++(*co)); // The old hub becomes the spoke, which is deleted if spoke() throws diff --git a/gecode/search/seq/rbs.hh b/gecode/search/seq/rbs.hh index 4ea474a991..610ecb2c21 100755 --- a/gecode/search/seq/rbs.hh +++ b/gecode/search/seq/rbs.hh @@ -40,6 +40,8 @@ #include +#include + namespace Gecode { namespace Search { namespace Seq { class RBS; @@ -53,10 +55,14 @@ namespace Gecode { namespace Search { namespace Seq { mutable Support::Mutex m; /// The failure limit for the engine unsigned long long int l; + /// The last cutoff, the failure budget of the current episode + unsigned long long int c; /// The stop object for the meta engine Stop* m_stop; /// Whether the engine was stopped bool e_stopped; + /// The largest failure count of a worker that the limit stopped + unsigned long long int e_fail; /// Accumulated statistics for the meta engine Statistics m_stat; public: @@ -72,10 +78,18 @@ namespace Gecode { namespace Search { namespace Seq { void nogood(unsigned long int n); /// Test hub status with meta statistics SpaceStatus status(Space* s); - /// Add statistics \a s and set the limit for the engine to \a l fails - void limit(const Statistics& s, unsigned long long int l); - /// Set the limit for the engine, which continues its search, to \a l fails - void extend(unsigned long long int l); + /// Add statistics \a s and start an episode with cutoff \a c + void limit(const Statistics& s, unsigned long long int c); + /// Add statistics \a s and start an episode with the last cutoff + void renew(const Statistics& s); + /** + * \brief Give the engine, which continues its search, a budget of \a c fails + * + * The budget counts from the failures of the worker that the limit + * stopped, as stop() compares the failures of each worker with the + * limit. The limit saturates instead of wrapping around. + */ + void extend(unsigned long long int c); /// Update statistics void update(const Search::Statistics& s); /// Return whether the engine has been stopped diff --git a/gecode/search/seq/rbs.hpp b/gecode/search/seq/rbs.hpp index a6d2464433..8938eca1e5 100755 --- a/gecode/search/seq/rbs.hpp +++ b/gecode/search/seq/rbs.hpp @@ -40,7 +40,7 @@ namespace Gecode { namespace Search { namespace Seq { forceinline RestartStop::RestartStop(Stop* s) - : l(0U), m_stop(s), e_stopped(false) {} + : l(0U), c(0U), m_stop(s), e_stopped(false), e_fail(0U) {} forceinline void RestartStop::restart(void) { @@ -61,18 +61,30 @@ namespace Gecode { namespace Search { namespace Seq { } forceinline void - RestartStop::limit(const Search::Statistics& s, unsigned long long int l0) { + RestartStop::limit(const Search::Statistics& s, unsigned long long int c0) { Support::Lock lock(m); - l = l0; + l = c = c0; m_stat += s; e_stopped = false; + e_fail = 0U; } forceinline void - RestartStop::extend(unsigned long long int l0) { + RestartStop::renew(const Search::Statistics& s) { Support::Lock lock(m); - l = l0; + l = c; + m_stat += s; + e_stopped = false; + e_fail = 0U; + } + + forceinline void + RestartStop::extend(unsigned long long int c0) { + Support::Lock lock(m); + c = c0; + l = (e_fail > ULLONG_MAX - c0) ? ULLONG_MAX : e_fail + c0; e_stopped = false; + e_fail = 0U; } forceinline void diff --git a/test/search.cpp b/test/search.cpp index 0ee71dd0c0..8993da97ad 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -44,8 +44,10 @@ #include "test/test.hh" +#include #include #include +#include #include #include #include @@ -4056,8 +4058,10 @@ namespace Test { } break; case Protocol::ContinueAtLimit: + // Finish instead of repeating a limit that leaves no budget if (hc.event() == MetaEvent::Limit) - hc.decision(MetaDecision::Continue); + hc.decision((log->hub.size() > 100U) ? MetaDecision::Finish : + MetaDecision::Continue); break; case Protocol::EmptyHub: return; @@ -4096,6 +4100,8 @@ namespace Test { FailAtStart, FailAtSolution, ContinueAtLimit, + ContinueThenRestart, + ContinueWithLargestCutoff, EngineConstrainsHub, PortfolioHubConstraint, Episodes, @@ -4271,6 +4277,66 @@ namespace Test { return false; return log.live == 0; } + /// Return how often hub() was called at Limit in episode \a e + static long int limits(const ProtocolLog& log, unsigned long int e) { + return static_cast( + std::count(log.hub.begin(),log.hub.end(), + std::make_pair(MetaEvent::Limit,e))); + } + /// Check that a restart after a solution uses the cutoff, not the extended limit + static bool continue_then_restart(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::ContinueAtLimit,log); + Gecode::RBS rbs(m,rbs_options(2)); + delete m; + for (int i=0; i<2; i++) { + ProtocolSpace* s = rbs.next(); + if (s == nullptr) + return false; + delete s; + } + } + // Each episode fails six times and so reaches the cutoff of two twice + return (limits(log,0UL) == 2L) && (limits(log,1UL) == 2L) && + (log.live == 0); + } + /// Cutoff generator whose values after the first are the largest possible + class LargestCutoff : public Gecode::Search::Cutoff { + protected: + /// The current value + unsigned long long int c; + public: + /// Initialize with first value \a c0 + explicit LargestCutoff(unsigned long long int c0) : c(c0) {} + unsigned long long int operator ()(void) const override { + return c; + } + unsigned long long int operator ++(void) override { + c = ULLONG_MAX; + return c; + } + Gecode::Search::Cutoff* copy(void) const override { + return new LargestCutoff(*this); + } + }; + /// Check that Continue with the largest cutoff does not wrap the limit around + static bool continue_with_largest_cutoff(void) { + ProtocolLog log; + { + ProtocolSpace* m = new ProtocolSpace(Protocol::ContinueAtLimit,log); + Gecode::Search::Options o; + o.threads = 1; + o.cutoff = new LargestCutoff(2); + Gecode::RBS rbs(m,o); + delete m; + ProtocolSpace* s = rbs.next(); + if (s == nullptr) + return false; + delete s; + } + return (limits(log,0UL) == 1L) && (log.live == 0); + } /// Check that RBS constrains the hub when hub() does nothing static bool engine_constrains_hub(void) { ProtocolLog log; @@ -4373,6 +4439,10 @@ namespace Test { return fail_at_solution(); case Scenario::ContinueAtLimit: return continue_at_limit(); + case Scenario::ContinueThenRestart: + return continue_then_restart(); + case Scenario::ContinueWithLargestCutoff: + return continue_with_largest_cutoff(); case Scenario::EngineConstrainsHub: return engine_constrains_hub(); case Scenario::PortfolioHubConstraint: @@ -4401,6 +4471,11 @@ namespace Test { ("FailAtSolution",MetaProtocol::Scenario::FailAtSolution); MetaProtocol meta_continue_at_limit ("ContinueAtLimit",MetaProtocol::Scenario::ContinueAtLimit); + MetaProtocol meta_continue_then_restart + ("ContinueThenRestart",MetaProtocol::Scenario::ContinueThenRestart); + MetaProtocol meta_continue_with_largest_cutoff + ("ContinueWithLargestCutoff", + MetaProtocol::Scenario::ContinueWithLargestCutoff); MetaProtocol meta_engine_constrains_hub ("EngineConstrainsHub",MetaProtocol::Scenario::EngineConstrainsHub); MetaProtocol meta_portfolio_hub_constraint From f50d613955aecf3dcffab7ff484ce6d930b636ec Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 24 Nov 2026 21:16:55 +0100 Subject: [PATCH 18/37] Report an incomplete search in the time mode of the driver The time mode printed the same summary for a search that ended without exhausting its search space, such as LDS at its discrepancy limit, as for an exhausted one. The solution mode already reported the difference. --- gecode/driver/script.hpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/gecode/driver/script.hpp b/gecode/driver/script.hpp index 8a83556fd2..204f767ba4 100755 --- a/gecode/driver/script.hpp +++ b/gecode/driver/script.hpp @@ -427,9 +427,9 @@ namespace Gecode { namespace Driver { CombinedStop::installCtrlHandler(false); Search::Statistics stat = e.statistics(); s_out << endl; - if (e.end_reason() == Search::EndReason::Incomplete) { - l_out << "Search engine finished without exhausting the search space" << '\n' << '\n'; - } else if (e.end_reason() == Search::EndReason::Limit) { + if (e.end_reason() == Search::EndReason::Incomplete) { + l_out << "Search engine finished without exhausting the search space" << '\n' << '\n'; + } else if (e.end_reason() == Search::EndReason::Limit) { l_out << "Search engine stopped..." << endl << "\treason: "; int r = static_cast(so.stop)->reason(stat,so); @@ -543,6 +543,7 @@ namespace Gecode { namespace Driver { Support::Timer t; double* ts = new double[o.samples()]; bool stopped = false; + bool incomplete = false; for (unsigned int ns = o.samples(); !stopped && ns--; ) { unsigned long long int s_l = (o.solutions() == 0) ? ULLONG_MAX : o.solutions(); @@ -576,6 +577,8 @@ namespace Gecode { namespace Driver { } while (s_n < s_l); if (e.end_reason() == Search::EndReason::Limit) stopped = true; + else if (e.end_reason() == Search::EndReason::Incomplete) + incomplete = true; } delete sok.stop; } @@ -592,6 +595,8 @@ namespace Gecode { namespace Driver { << setprecision(6) << m << "ms" << setprecision(2) << " (" << d << "% deviation)" << endl; + if (incomplete) + l_out << "\tsearch finished without exhausting the search space" << endl; } delete [] ts; } From ad4cea1866dc1d26f89d393124509d2593207128 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 24 Nov 2026 21:20:48 +0100 Subject: [PATCH 19/37] Keep AStar and CABS exhausted when their stop object fires later After a search had exhausted its search space, a later call to next() checked the stop object before finding that no work was left. When the stop object fired, for example at a time limit, end_reason() reported a limit instead of the proof. --- gecode/search/astar.cpp | 5 ++-- gecode/search/cabs.cpp | 11 ++++++-- gecode/search/par/frontier.cpp | 15 ++++++++-- gecode/search/par/frontier.hh | 2 ++ gecode/search/seq/cabs.hh | 2 ++ test/search.cpp | 50 ++++++++++++++++++++++++++++++++++ 6 files changed, 78 insertions(+), 7 deletions(-) diff --git a/gecode/search/astar.cpp b/gecode/search/astar.cpp index 4bbef62db7..cb2d36624a 100644 --- a/gecode/search/astar.cpp +++ b/gecode/search/astar.cpp @@ -154,11 +154,12 @@ namespace Gecode { namespace Search { namespace Seq { AStar::next(void) { start(); while (true) { + // An exhausted search is complete, even when a limit has been reached + if (!expansion && queue.empty()) + return nullptr; if (stop_seq(opt)) return nullptr; if (!expansion) { - if (queue.empty()) - return nullptr; Entry e = queue.pop(); std::unique_ptr s(e.space); if (!best.improves(e.bound)) { diff --git a/gecode/search/cabs.cpp b/gecode/search/cabs.cpp index e9ab0c9b8f..2b3b6648bb 100644 --- a/gecode/search/cabs.cpp +++ b/gecode/search/cabs.cpp @@ -150,7 +150,7 @@ namespace Gecode { namespace Search { namespace Seq { priority{guidance.sense,static_cast(guidance.rank)}, candidates(priority,guidance.dominates && guidance.dominance_key), order(0), status(SS_FAILED), depth(0), revision(0), counted(false), - best(guidance.sense), _limited(false) { + best(guidance.sense), _limited(false), _exhausted(false) { initialize(s,o.clone); } @@ -236,12 +236,17 @@ namespace Gecode { namespace Search { namespace Seq { return nullptr; } start(); + // An exhausted search is complete, even when a limit has been reached + if (_exhausted) + return nullptr; while (true) { if (stop_seq(opt)) return nullptr; if (!expansion) { - if (layer.empty() && !advance()) + if (layer.empty() && !advance()) { + _exhausted = !_limited; return nullptr; + } if (!expansion) { Entry e = layer.pop(); std::unique_ptr s(e.space); @@ -324,7 +329,7 @@ namespace Gecode { namespace Search { namespace Seq { order = 0; revision = 0; depth = 0; - counted = _limited = false; + counted = _limited = _exhausted = false; Worker::reset(); initialize(s,false); // The root is owned by the engine after initialize returns diff --git a/gecode/search/par/frontier.cpp b/gecode/search/par/frontier.cpp index 38b001ae04..a16f4080fe 100644 --- a/gecode/search/par/frontier.cpp +++ b/gecode/search/par/frontier.cpp @@ -60,6 +60,7 @@ namespace Gecode { namespace Search { namespace Par { guidance(*o.guidance), best(guidance.sense), order(0), pending(heap), n_pending(0), runners(nullptr), active(0), running(false), shutdown(false), _stopped(false), _limited(false), + _exhausted(false), end(EndReason::NotEnded), batch(1), keyed(false) {} @@ -213,8 +214,10 @@ namespace Gecode { namespace Search { namespace Par { return; } while (running && enabled && (task == nullptr)) { - if ((n_pending == 0) && !open() && (active == 0) && !advance()) + if ((n_pending == 0) && !open() && (active == 0) && !advance()) { running = false; + _exhausted = !_limited; + } if (!running || ((n_pending == 0) && !open())) break; if (n_pending > 0) { @@ -339,6 +342,12 @@ namespace Gecode { namespace Search { namespace Par { end = EndReason::Incomplete; return nullptr; } + // An exhausted search is complete, even when a limit has been reached + if (_exhausted) { + _stopped = false; + end = EndReason::Exhausted; + return nullptr; + } _stopped = false; running = true; } @@ -355,6 +364,8 @@ namespace Gecode { namespace Search { namespace Par { end = EndReason::NotEnded; else if (_limited) end = EndReason::Incomplete; + else if (_exhausted) + end = EndReason::Exhausted; else end = _stopped ? EndReason::Limit : EndReason::Exhausted; return s; @@ -394,7 +405,7 @@ namespace Gecode { namespace Search { namespace Par { best.reset(); solution.reset(); order = 0; - _stopped = _limited = false; + _stopped = _limited = _exhausted = false; end = EndReason::NotEnded; error = nullptr; stat.reset(); diff --git a/gecode/search/par/frontier.hh b/gecode/search/par/frontier.hh index 63fd89a35f..ebb0ee6bfe 100644 --- a/gecode/search/par/frontier.hh +++ b/gecode/search/par/frontier.hh @@ -110,6 +110,8 @@ namespace Gecode { namespace Search { namespace Par { unsigned int active; /// Whether search is running, being shut down, stopped, or limited bool running, shutdown, _stopped, _limited; + /// Whether search has exhausted its search space + bool _exhausted; /// Why the last call to next() returned no solution EndReason end; /// First exception thrown by a worker diff --git a/gecode/search/seq/cabs.hh b/gecode/search/seq/cabs.hh index 05f41e2842..9b1023a30d 100644 --- a/gecode/search/seq/cabs.hh +++ b/gecode/search/seq/cabs.hh @@ -73,6 +73,8 @@ namespace Gecode { namespace Search { namespace Seq { Incumbent best; /// Whether search stopped at the width or frontier limit bool _limited; + /// Whether search has exhausted its search space + bool _exhausted; /// Offer node \a s at depth \a d to the next layer, false if no room bool admit(std::unique_ptr s, unsigned long int d); /// Make \a s the incumbent and return a copy, if it improves diff --git a/test/search.cpp b/test/search.cpp index 8993da97ad..0a7efa4691 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -303,6 +303,56 @@ namespace Test { Heuristic astar_test("AStar"); Heuristic cabs_test("CABS"); + /// Stop object that stops once it is switched on + class Switch : public Gecode::Search::Stop { + public: + /// Whether search must stop + std::atomic on{false}; + bool stop(const Gecode::Search::Statistics&, + const Gecode::Search::Options&) override { + return on.load(); + } + }; + + /// A heuristic search stays exhausted when its stop object fires later + template class E> + class HeuristicExhausted : public Base { + public: + HeuristicExhausted(const std::string& name) + : Base("Search::"+name+"::Exhausted") {} + bool run(void) override { + for (unsigned int threads : {1U,2U}) { +#ifndef GECODE_HAS_THREADS + if (threads > 1U) continue; +#endif + TreeSpace root(TreeSpace::random(_rand),false); + Gecode::Search::HeuristicGuidance g = + TreeSpace::guidance(false,false,false,false); + Switch stop; + Gecode::Search::Options o; + o.threads = threads; + o.guidance = &g; + o.stop = &stop; + E e(&root,o); + while (TreeSpace* s = e.next()) + delete s; + if (e.end_reason() != EndReason::Exhausted) + return false; + stop.on = true; + if (TreeSpace* s = e.next()) { + delete s; + return false; + } + if (e.end_reason() != EndReason::Exhausted) + return false; + } + return true; + } + }; + + HeuristicExhausted astar_exhausted("AStar"); + HeuristicExhausted cabs_exhausted("CABS"); + /// Portfolio of BAB, A*, and CABS assets class HeuristicPortfolio : public Base { /// Stop object that never stops but takes some time From a88bf74d1800bd96e126d46f94139ccb606a2070 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 24 Nov 2026 21:26:51 +0100 Subject: [PATCH 20/37] Forget the end reason of parallel DFS and BAB on reset After a reset, end_reason() of a parallel engine still reported how the previous search ended until the next call to next(). The sequential engines already report NotEnded. --- gecode/search/par/bab.hpp | 1 + gecode/search/par/dfs.hpp | 1 + test/search.cpp | 30 ++++++++++++++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/gecode/search/par/bab.hpp b/gecode/search/par/bab.hpp index e048391bf0..218e310c34 100755 --- a/gecode/search/par/bab.hpp +++ b/gecode/search/par/bab.hpp @@ -452,6 +452,7 @@ namespace Gecode { namespace Search { namespace Par { delete best; best = nullptr; n_busy = workers(); + this->end = EndReason::NotEnded; } for (unsigned int i=1U; ireset(nullptr,0); diff --git a/gecode/search/par/dfs.hpp b/gecode/search/par/dfs.hpp index 12a94b1cb8..8e5a62c653 100755 --- a/gecode/search/par/dfs.hpp +++ b/gecode/search/par/dfs.hpp @@ -341,6 +341,7 @@ namespace Gecode { namespace Search { namespace Par { e_reset_ack_start.wait(); // All workers are marked as busy again n_busy = workers(); + this->end = EndReason::NotEnded; for (unsigned int i=1U; ireset(nullptr,0); worker(0U)->reset(s,opt().nogoods_limit); diff --git a/test/search.cpp b/test/search.cpp index 0a7efa4691..55259ca777 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -3416,6 +3416,36 @@ namespace Test { ExhaustedAtLimit exhausted_at_limit; + /// Resetting an engine forgets why its last search ended + class ResetEndReason : public Base { + static bool test(Gecode::Search::Engine* e) { + std::unique_ptr owned(e); + if ((e->next() != nullptr) || (e->end_reason() != EndReason::Exhausted)) + return false; + NoSolution root; + e->reset(root.clone()); + return e->end_reason() == EndReason::NotEnded; + } + public: + ResetEndReason(void) : Base("Search::ResetEndReason") {} + bool run(void) override { + for (unsigned int t : {1U,2U}) { +#ifndef GECODE_HAS_THREADS + if (t > 1U) continue; +#endif + NoSolution root; + Gecode::Search::Options o; + o.threads = t; + if (!test(Gecode::Search::dfsengine(&root,o)) || + !test(Gecode::Search::babengine(&root,o))) + return false; + } + return true; + } + }; + + ResetEndReason reset_end_reason; + /// LDS reports an incomplete search at its discrepancy limit class LDSIncomplete : public Base { static EndReason end_reason(unsigned int d_l) { From c13dffe2776cf16f083d614f63108c10a1135a07 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 24 Nov 2026 21:26:51 +0100 Subject: [PATCH 21/37] Count a worker that steals work before its victim can go idle A thief released the path lock of its victim before it counted itself as busy. In between, the victim could finish its remaining work and report idle, so that the engine saw no busy worker and reported an exhausted search while the thief still held a subtree. The thief now counts itself while it holds the path lock. The count is atomic, so this takes no lock on m_search, which is acquired before the path locks elsewhere. --- gecode/search/par/engine.hh | 10 ++++++++-- gecode/search/par/engine.hpp | 16 ++++++++-------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/gecode/search/par/engine.hh b/gecode/search/par/engine.hh index 50a1be64a1..49bb533745 100644 --- a/gecode/search/par/engine.hh +++ b/gecode/search/par/engine.hh @@ -238,8 +238,14 @@ namespace Gecode { namespace Search { namespace Par { Support::Event e_search; /// Queue of solutions Support::DynamicQueue solutions; - /// Number of busy workers - volatile unsigned int n_busy; + /** + * \brief Number of busy workers + * + * A worker that steals work counts itself while it holds the path lock + * of the victim, which is busy. So the count never reaches zero while a + * stolen subtree is still uncounted, and it stays zero once it is. + */ + std::atomic n_busy; /// Whether a worker had been stopped std::atomic has_stopped; /// Why the last call to next() returned no solution diff --git a/gecode/search/par/engine.hpp b/gecode/search/par/engine.hpp index 00233bc2b6..f466b67516 100644 --- a/gecode/search/par/engine.hpp +++ b/gecode/search/par/engine.hpp @@ -125,8 +125,8 @@ namespace Gecode { namespace Search { namespace Par { _opt(o), scheduler_enabled(false), scheduler_fast_admit(nullptr), scheduler_worker(nullptr), scheduler_requested(workers()), - scheduler_leases(0U), scheduler_cursor(0U), scheduler_generation(0U), _cmd(C_WAIT), solutions(heap), - end(EndReason::NotEnded) { + scheduler_leases(0U), scheduler_cursor(0U), scheduler_generation(0U), + _cmd(C_WAIT), solutions(heap), end(EndReason::NotEnded) { // Initialize termination information _n_term_not_ack = workers(); _n_not_terminated = workers(); @@ -367,10 +367,10 @@ namespace Gecode { namespace Search { namespace Par { template forceinline void Engine::busy(void) { - m_search.acquire(); - assert(n_busy > 0); - n_busy++; - m_search.release(); + // Called with the path lock of a busy victim, so without m_search + unsigned int n = n_busy.fetch_add(1U); + assert(n > 0); + (void) n; } template @@ -499,10 +499,10 @@ namespace Gecode { namespace Search { namespace Par { */ m.acquire(); Space* s = path.steal() ? path.steal(*this,d,myt,ot) : nullptr; - m.release(); - // Tell that there will be one more busy worker + // Count the thief before this worker can report that it is idle if (s != nullptr) engine().busy(); + m.release(); return s; } From 66a1a3fd57828962129f67e0f1bcc187b20259b8 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 24 Nov 2026 21:30:07 +0100 Subject: [PATCH 22/37] Run a single asset of a sequential portfolio without slices A single asset whose spoke is partial runs in a sequential portfolio, so that its exhaustion is reported as incomplete. With a slice of zero, its engine stopped before its first node and the portfolio retried forever. A single asset now has no slice limit. --- gecode/search/seq/pbs.hpp | 5 +++-- test/search.cpp | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index 64462dca0a..cfc9f72742 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -101,7 +101,8 @@ namespace Gecode { namespace Search { namespace Seq { assets(heap.alloc(n)), n_assets(n), cur(0), end(EndReason::NotEnded) { ssi.cause = PortfolioStopCause::None; - ssi.l = opt.slice; + // A single asset needs no slices, and a slice of zero would never end + ssi.l = (n == 1U) ? ULLONG_MAX : opt.slice; for (unsigned int i=0U; i(s[i]),c[i]); @@ -171,7 +172,7 @@ namespace Gecode { namespace Search { namespace Seq { assets[cur] = assets[--n_assets]; if (n_assets == 1) // Disable stopping by setting a high limit - ssi.l = ULONG_MAX; + ssi.l = ULLONG_MAX; } if (cur == n_assets) cur = 0; diff --git a/test/search.cpp b/test/search.cpp index 55259ca777..aec578b534 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -3765,6 +3765,42 @@ namespace Test { PBSExhaustedAsset pbs_exhausted_asset; + /// A single asset of a sequential portfolio runs without slices + class PBSSingleAssetSlice : public Base { + /// Space without a solution whose portfolio spoke is partial + class PartialSpoke : public NoSolution { + public: + PartialSpoke(void) = default; + PartialSpoke(PartialSpoke& s) : NoSolution(s) {} + Gecode::Space* copy(void) override { + return new PartialSpoke(*this); + } + void spoke(Gecode::SpokeContext& sc) override { + sc.coverage(Gecode::SpokeCoverage::Partial); + } + }; + public: + PBSSingleAssetSlice(void) : Base("Search::PBS::SingleAssetSlice") {} + bool run(void) override { + PartialSpoke root; + // Stops after 1000 checks in case the asset makes no progress + FailureLimit l(ULLONG_MAX); + Gecode::Search::Options o; + o.assets = 1; + o.threads = 1; + o.slice = 0; + o.stop = &l; + Gecode::PBS pbs(&root,o); + if (PartialSpoke* s = pbs.next()) { + delete s; + return false; + } + return pbs.end_reason() == EndReason::Incomplete; + } + }; + + PBSSingleAssetSlice pbs_single_asset_slice; + /// The stop object of a portfolio sees the failures of all assets class PBSPortfolioStop : public Base { /// Whether restart-based assets stop at a portfolio-wide failure limit From d1bbca05848f9550ea50593d5fd38f4ebb6cf0fb Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 24 Nov 2026 21:30:07 +0100 Subject: [PATCH 23/37] Keep the most important stop cause of a portfolio asset The workers of a parallel asset can check the stop object concurrently, and each recorded its own cause, so a later asset or slice stop could replace a portfolio stop. The portfolio then continued instead of returning Limit. A cause now replaces only one of lower priority. --- gecode/search/par/pbs.cpp | 6 +++--- gecode/search/seq/pbs.cpp | 6 +++--- gecode/search/seq/pbs.hh | 4 ++-- gecode/search/support.hh | 19 ++++++++++++++++++- 4 files changed, 26 insertions(+), 9 deletions(-) diff --git a/gecode/search/par/pbs.cpp b/gecode/search/par/pbs.cpp index 94ef331ef0..35f99504ad 100644 --- a/gecode/search/par/pbs.cpp +++ b/gecode/search/par/pbs.cpp @@ -53,15 +53,15 @@ namespace Gecode { namespace Search { namespace Par { bool PortfolioStop::stop(const Statistics& s, const Options& o) { if (tostop->load(std::memory_order_acquire)) { - _cause.store(PortfolioStopCause::Interrupt, std::memory_order_relaxed); + pbs_record_cause(_cause,PortfolioStopCause::Interrupt); return true; } if ((po != nullptr) && po->stop(ps->update(asset,s),o)) { - _cause.store(PortfolioStopCause::Portfolio, std::memory_order_relaxed); + pbs_record_cause(_cause,PortfolioStopCause::Portfolio); return true; } if ((so != nullptr) && so->stop(s,o)) { - _cause.store(PortfolioStopCause::Asset, std::memory_order_relaxed); + pbs_record_cause(_cause,PortfolioStopCause::Asset); return true; } return false; diff --git a/gecode/search/seq/pbs.cpp b/gecode/search/seq/pbs.cpp index 64c7909a35..4ed990a475 100644 --- a/gecode/search/seq/pbs.cpp +++ b/gecode/search/seq/pbs.cpp @@ -38,15 +38,15 @@ namespace Gecode { namespace Search { namespace Seq { bool PortfolioStop::stop(const Statistics& s, const Options& o) { if ((po != nullptr) && po->stop(ssi->others + s,o)) { - ssi->cause = PortfolioStopCause::Portfolio; + pbs_record_cause(ssi->cause,PortfolioStopCause::Portfolio); return true; } if ((so != nullptr) && so->stop(s,o)) { - ssi->cause = PortfolioStopCause::Asset; + pbs_record_cause(ssi->cause,PortfolioStopCause::Asset); return true; } if (s.fail >= ssi->l) { - ssi->cause = PortfolioStopCause::Slice; + pbs_record_cause(ssi->cause,PortfolioStopCause::Slice); return true; } return false; diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index 739fe81eae..49285329cd 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -42,8 +42,8 @@ namespace Gecode { namespace Search { namespace Seq { /// Shared stop information class SharedStopInfo { public: - /// Which stop object stopped the running asset - PortfolioStopCause cause; + /// Which stop object stopped the running asset, its workers can run in parallel + std::atomic cause; /// The current failure limit, incremented for each slice unsigned long long int l; /// Statistics of the portfolio except for the running asset diff --git a/gecode/search/support.hh b/gecode/search/support.hh index 8fe8b72e9b..bdc54954a1 100644 --- a/gecode/search/support.hh +++ b/gecode/search/support.hh @@ -36,6 +36,8 @@ #include +#include + namespace Gecode { namespace Search { /// Whether incoming solution \a s should replace incumbent \a b @@ -73,7 +75,13 @@ namespace Gecode { namespace Search { return (r == EndReason::Exhausted) && (c != SpokeCoverage::Partial); } - /// Which stop object stopped an asset of a portfolio + /** + * \brief Which stop object stopped an asset of a portfolio + * + * The causes are listed in increasing priority. When the workers of a + * parallel asset stop for different causes, the one of highest priority + * is kept (see pbs_record_cause()). + */ enum class PortfolioStopCause : unsigned char { None, ///< No stop object has stopped the asset Slice, ///< The asset used up its slice of a sequential portfolio @@ -82,6 +90,15 @@ namespace Gecode { namespace Search { Portfolio, ///< The stop object of the portfolio }; + /// Record cause \a c in \a cause unless a cause of higher priority is recorded + forceinline void + pbs_record_cause(std::atomic& cause, + PortfolioStopCause c) { + PortfolioStopCause r = cause.load(std::memory_order_relaxed); + while ((r < c) && + !cause.compare_exchange_weak(r,c,std::memory_order_relaxed)) {} + } + /// Virtualize a worker to an engine template class WorkerToEngine : public Engine { From d6a89cf4b74bb1572e6af38e0dd67e91075df54f Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 24 Nov 2026 21:34:37 +0100 Subject: [PATCH 24/37] Check the end reason more strictly in search tests The no-goods test accepted any end of the stopped search, so it could pass without posting a no-good. The RBS test with an objective accepted an optimum without an exhausted search. The dispatch tests for an exhausted spoke of full or reduced coverage declared that coverage for a spoke that had removed the remaining solutions of the hub. Their hub now has no solution left, and the spoke proves that by search. --- test/nogoods.cpp | 13 ++++++++++--- test/search.cpp | 30 ++++++++++++++++++++++-------- 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/test/nogoods.cpp b/test/nogoods.cpp index a7964ed174..e73258b761 100644 --- a/test/nogoods.cpp +++ b/test/nogoods.cpp @@ -231,6 +231,8 @@ namespace Test { Model* m = new Model(vb,a,n); // Solution without no-goods Model* s_plain = dfs(m); + // Whether the search ended with a solution or exhausted + bool ended = true; // Stop and re-start for a while to collect no-goods { Search::NodeStop ns(Model::nodeinc()); @@ -241,9 +243,14 @@ namespace Test { Search::Engine* e = Search::dfsengine(m,o); while (true) { Model* s = static_cast(e->next()); - delete s; - if (e->end_reason() != Search::EndReason::Limit) + if (s != nullptr) { + delete s; break; + } + if (e->end_reason() != Search::EndReason::Limit) { + ended = e->end_reason() == Search::EndReason::Exhausted; + break; + } // Add no-goods e->nogoods().post(*m); ns.limit(ns.limit()+Model::nodeinc()); @@ -253,7 +260,7 @@ namespace Test { // Compare whether the a or the same solution is found with no-goods Model* s_nogoods = dfs(m); - bool ok = ((s_nogoods != nullptr) && + bool ok = ended && ((s_nogoods != nullptr) && ((t != 1) || s_plain->same(*s_nogoods))); delete m; diff --git a/test/search.cpp b/test/search.cpp index aec578b534..29e17346f0 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -752,7 +752,10 @@ namespace Test { MetaDecision solution_decision = MetaDecision::Restart; /// Coverage that spoke() declares after a solution SpokeCoverage solution_spoke_coverage = SpokeCoverage::Full; + /// Whether spoke() fails after a solution bool fail_solution_spoke = false; + /// Whether hub() leaves no solution after a solution, without failing + bool empty_hub_after_solution = false; bool nogood_model = false; /// Whether the model posts a branching on x bool model_branching = true; @@ -771,7 +774,7 @@ namespace Test { IntVar x; /// Optional queens model used to force restart no-good extraction IntVarArray q; - /// Optional variables without a solution, used to reach the cutoff + /// Optional variables without a solution, to reach the cutoff or empty the hub IntVarArray y; /// Shared hook observations and configuration MetaDispatchState* state; @@ -792,8 +795,14 @@ namespace Test { Space::hub(hc); if (hc.nogoods().ng() > 0) state->nogood_handoffs.fetch_add(1, std::memory_order_relaxed); - if (hc.event() == MetaEvent::Solution) + if (hc.event() == MetaEvent::Solution) { + if (state->empty_hub_after_solution) { + // Four distinct values from three fail only during search. + distinct(*this, y, IPL_VAL); + Gecode::branch(*this, y, INT_VAR_NONE(), INT_VAL_MIN()); + } hc.decision(state->solution_decision); + } } /// Record and implement a Spoke callback void @@ -825,7 +834,7 @@ namespace Test { public: /// Initialize with shared observations \a s MetaDispatchSpace(MetaDispatchState& s) - : x(*this, 0, 1), q(*this, s.nogood_model ? 8 : 0, 0, 7), y(*this, s.limit_first_spoke ? 4 : 0, 0, 2), + : x(*this, 0, 1), q(*this, s.nogood_model ? 8 : 0, 0, 7), y(*this, (s.limit_first_spoke || s.empty_hub_after_solution) ? 4 : 0, 0, 2), state(&s), restart_role(RestartRole::Hub), portfolio_asset(-1) { state->live_spaces.fetch_add(1, std::memory_order_relaxed); if (state->nogood_model) { @@ -1013,11 +1022,15 @@ namespace Test { } /// Run one RBS dispatch scenario static bool - rbs(MetaDecision solution_decision, bool fail_solution_spoke, + rbs(MetaDecision solution_decision, bool empty_after_solution, SpokeCoverage solution_spoke_coverage) { MetaDispatchState state; state.solution_decision = solution_decision; - state.fail_solution_spoke = fail_solution_spoke; + // A spoke that is not partial keeps the solutions of the hub, so + // only a partial spoke may remove them + const bool partial = solution_spoke_coverage == SpokeCoverage::Partial; + state.fail_solution_spoke = empty_after_solution && partial; + state.empty_hub_after_solution = empty_after_solution && !partial; state.solution_spoke_coverage = solution_spoke_coverage; HubSpokeDispatchSpace* m = new HubSpokeDispatchSpace(state); @@ -1035,13 +1048,13 @@ namespace Test { const unsigned int solution = event_bit(MetaEvent::Solution); const unsigned int exhausted = event_bit(MetaEvent::Exhausted); HubSpokeDispatchSpace* second = search.next(); - if (!fail_solution_spoke) { + if (!empty_after_solution) { const bool restart = solution_decision == MetaDecision::Restart; ok = ok && (second != nullptr) && holds(state.hub_calls, 2U) && holds(state.spoke_calls, restart ? 2U : 1U) && holds(state.hub_events, start | solution) && holds(state.spoke_events, start | (restart ? solution : 0U)); - } else if (solution_spoke_coverage != SpokeCoverage::Partial) { + } else if (!partial) { // Exhausting a spoke that is not partial is a proof ok = ok && (second == nullptr) && (search.end_reason() == EndReason::Exhausted) && @@ -2930,7 +2943,8 @@ namespace Test { } if (htc == HTC_NONE) return (n == 0) && (rbs.end_reason() == EndReason::Exhausted); - bool ok = improving && (b != nullptr) && b->best(); + bool ok = improving && (b != nullptr) && b->best() && + (rbs.end_reason() == EndReason::Exhausted); delete b; return ok; } From 9f469501a7aa8a4cbf47c51bdf8a9ef2c15f4217 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 24 Nov 2026 21:35:09 +0100 Subject: [PATCH 25/37] Fix the accounting and launch of parallel portfolio assets - An asset that ended without a proof could have done work after its last stop check, such as a final failure. The portfolio stop object now sees the final statistics of the asset. - A portfolio stop that arrived together with solutions was cleared once the solutions had been returned, so next() never reported the limit. It is now reported after the solutions. - When an asset thread could not be started, next() threw with its mutex held, and the destructor waited for a completion that the asset never signalled. The asset's completion is now restored, the started assets are stopped and awaited, and the failure is reported again by later calls. A fault-injection point at thread launch tests this. --- gecode/search/par/pbs.hh | 15 +++++++++ gecode/search/par/pbs.hpp | 53 ++++++++++++++++++++++++++++++-- gecode/support/failpoint.hpp | 3 +- gecode/support/thread/thread.hpp | 3 ++ test/fault.cpp | 53 ++++++++++++++++++++++++++++++++ 5 files changed, 124 insertions(+), 3 deletions(-) diff --git a/gecode/search/par/pbs.hh b/gecode/search/par/pbs.hh index b99626f23d..5c48ba69dd 100644 --- a/gecode/search/par/pbs.hh +++ b/gecode/search/par/pbs.hh @@ -101,6 +101,8 @@ namespace Gecode { namespace Search { namespace Par { unsigned int i); /// Return true if portfolio engine must be stopped virtual bool stop(const Statistics& s, const Options& o); + /// Record the final statistics \a s of the asset with the portfolio + void record(const Statistics& s); /// Wake workers so that a paused asset can observe the portfolio stop void wake(void); /// Forget which stop object stopped the asset @@ -157,6 +159,10 @@ namespace Gecode { namespace Search { namespace Par { virtual Support::Terminator* terminator(void) const; /// Wait for the asset to complete its current run void wait(void); + /// Restore the completion of a run that could not be started + void restore(void); + /// Record the final statistics of the asset with the portfolio + void record(void); /// Wake a paused asset so that it can observe the portfolio stop void wake(void); /// Constrain with better solution \a b @@ -256,6 +262,15 @@ namespace Gecode { namespace Search { namespace Par { bool report(Asset* asset, Space* s); /// Process failure from asset void fail(void); + /** + * \brief Handle that asset \a i could not be started + * + * Of the \a n assets that the current round did not start, the first + * is \a i. Must be called with the mutex held, from the handler of the + * exception, and returns with the mutex released once the started + * assets are idle. + */ + void launch_failed(unsigned int i, unsigned int n); /** * The key invariant of the engine is as follows: * - n_busy is always zero outside the next() function. diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index 01f811fe72..1da78e074e 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -158,6 +158,11 @@ namespace Gecode { namespace Search { namespace Par { return _cause.load(std::memory_order_relaxed); } + forceinline void + PortfolioStop::record(const Statistics& s) { + (void) ps->update(asset,s); + } + forceinline void PortfolioStop::share(std::atomic* ts, PortfolioStatistics* ps0, unsigned int i) { tostop = ts; @@ -198,6 +203,16 @@ namespace Gecode { namespace Search { namespace Par { } template forceinline void + Asset::restore(void) { + completion.terminated(); + } + template + forceinline void + Asset::record(void) { + static_cast(stop)->record(engine->statistics()); + } + template + forceinline void Asset::wake(void) { static_cast(stop)->wake(); } @@ -288,6 +303,8 @@ namespace Gecode { namespace Search { namespace Par { wake = true; } else { // The asset ended without a proof, move it to inactive + // Its last stop check might not include its final work + asset->record(); unsigned int i=0; while (assets[i] != asset) i++; @@ -322,6 +339,24 @@ namespace Gecode { namespace Search { namespace Par { m.release(); } + template + void + PBS::launch_failed(unsigned int i, unsigned int n) { + // The asset did not start and so will not signal its completion + assets[i]->restore(); + if (failure == nullptr) + failure = std::current_exception(); + // Stop the assets that started and wait until they are idle + tostop.store(true, std::memory_order_release); + for (unsigned int j=0U; jwake(); + n_busy -= n; + bool started = n_busy > 0; + m.release(); + if (started) + idle.wait(); + } + template void Asset::run(void) { @@ -346,7 +381,14 @@ namespace Gecode { namespace Search { namespace Par { std::rethrow_exception(f); } if (solutions.empty()) { - portfolio_stop.store(false, std::memory_order_release); + if (!exhausted && portfolio_stop.load(std::memory_order_acquire)) { + // Report a portfolio stop that arrived with the solutions returned + // since, the next call resumes the assets + portfolio_stop.store(false, std::memory_order_release); + end = EndReason::Limit; + m.release(); + return nullptr; + } // Resume the assets that their own stop objects stopped for (unsigned int i=0U; iparked(false); @@ -369,12 +411,19 @@ namespace Gecode { namespace Search { namespace Par { // Run all active assets that are not parked n_busy = n_run; + unsigned int n_started = 0; for (unsigned int i=0U; iparked()) { // Consume the previous completion before reusing this asset. The // initial signal handles the first submission. assets[i]->wait(); - Support::Thread::run(assets[i]); + try { + Support::Thread::run(assets[i]); + } catch (...) { + launch_failed(i,n_run-n_started); + throw; + } + n_started++; } m.release(); // Wait for all assets to become idle diff --git a/gecode/support/failpoint.hpp b/gecode/support/failpoint.hpp index bfdabd1d12..18f920c7ec 100644 --- a/gecode/support/failpoint.hpp +++ b/gecode/support/failpoint.hpp @@ -56,7 +56,8 @@ namespace Gecode { namespace Support { namespace FailPoint { LocalObjectCopy, SpaceDisposeNoticeArray, SpaceDisposalArray, - MiniModel + MiniModel, + ThreadLaunch }; /// Reset all failpoint state diff --git a/gecode/support/thread/thread.hpp b/gecode/support/thread/thread.hpp index bd4408d39e..a7327479a7 100644 --- a/gecode/support/thread/thread.hpp +++ b/gecode/support/thread/thread.hpp @@ -175,6 +175,9 @@ namespace Gecode { namespace Support { } inline void Thread::run(Runnable* r) { +#ifdef GECODE_HAS_FAULT_INJECTION + FailPoint::check(FailPoint::Phase::ThreadLaunch); +#endif m()->acquire(); if (idle != nullptr) { Run* i = idle; diff --git a/test/fault.cpp b/test/fault.cpp index fb4a4847a6..cce3232fc4 100644 --- a/test/fault.cpp +++ b/test/fault.cpp @@ -886,6 +886,59 @@ namespace Test { namespace Fault { } } +#ifdef GECODE_HAS_THREADS + /// Space with two solutions whose portfolio hub keeps its branchers + class PortfolioSpace : public Space { + public: + IntVar x; + PortfolioSpace(void) : x(*this,0,1) { + branch(*this,x,INT_VAL_MIN()); + } + PortfolioSpace(PortfolioSpace& s) : Space(s) { + x.update(*this,s.x); + } + virtual Space* copy(void) { + return new PortfolioSpace(*this); + } + virtual void hub(HubContext&) {} + }; + + /// A parallel portfolio reports an asset it cannot start and stays usable + bool portfolio_launch_failure(void) { + FaultScope scope; + PortfolioSpace root; + Search::Options o; + o.assets = 3; + o.threads = 3; + PBS pbs(&root,o); + // The first asset starts, the second does not + Support::FailPoint::fail_after(Phase::ThreadLaunch,1); + try { + delete pbs.next(); + return false; + } catch (const MemoryExhausted&) {} + Support::FailPoint::reset(); + // The portfolio reports the failure again, its destructor then waits + // only for the asset that started + try { + delete pbs.next(); + return false; + } catch (const MemoryExhausted&) {} + return true; + } + + class PortfolioLaunchFailure : public Base { + public: + PortfolioLaunchFailure(void) + : Base("Fault::Search::PortfolioLaunchFailure") {} + virtual bool run(void) { + return portfolio_launch_failure(); + } + }; + + PortfolioLaunchFailure portfolio_launch_failure_test; +#endif + class FaultBoolMisc : public BoolExpr::Misc { public: static int disposed; From 040b349840fba883e78aebce13301b08eea058bf Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 24 Nov 2026 21:35:09 +0100 Subject: [PATCH 26/37] Document the RBS hook calls and the PBS cutoff and statistics rules - RBS calls hub() only while search continues, and rbs() never calls it for its solution. - A single PBS asset of full or reduced coverage takes the cutoff itself, not a copy. - A parallel asset contributes the statistics of one worker to the portfolio stop object, and an ended asset its final statistics. - Copies of a random cutoff draw from different seeds, which need not give different values. - SpokeNoBrancher applies only to a spoke that has not failed. --- gecode/search.hh | 61 +++++++++++++++++++++++++++++++----------------- 1 file changed, 40 insertions(+), 21 deletions(-) diff --git a/gecode/search.hh b/gecode/search.hh index cdf3c4ebfc..a7c2e917a1 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -661,8 +661,8 @@ namespace Gecode { namespace Search { * The copy draws its values, starting with its current one, from a * seed that depends on the state of this generator and on how many * copies of it have been made before. Copies made one after the - * other thus have different sequences, so that the assets of a - * portfolio restart at different times, and the same program + * other thus draw from different seeds, so that the assets of a + * portfolio usually restart at different times, and the same program * creates the same sequences. */ virtual Cutoff* copy(void) const; @@ -1521,11 +1521,16 @@ namespace Gecode { * and * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() on its hub when search starts and after each - * episode, and spoke() on each spoke it clones from the hub. When \a E - * is a best solution engine, the engine constrains the hub by each - * solution before it calls hub(). See Space::hub() and Space::spoke() - * for details. + * The engine calls hub() on its hub when search starts and when an + * episode ends while search continues: after a solution, at the + * cutoff, and when the search of a spoke ends without a proof. When a + * spoke with SpokeCoverage::Full or SpokeCoverage::Reduced exhausts its + * search space, search ends without a call to hub(). The engine calls + * hub() for a solution in the next call to next(). The engine calls + * spoke() on each spoke it clones from the hub. When \a E is a best + * solution engine, the engine constrains the hub by each solution + * before it calls hub(). See Space::hub() and Space::spoke() for + * details. * * \ingroup TaskModelSearch */ @@ -1555,11 +1560,17 @@ namespace Gecode { * and * \code virtual void spoke(SpokeContext& sc) \endcode * - * The engine calls hub() on its hub when search starts and after each - * episode, and spoke() on each spoke it clones from the hub. When \a E - * is a best solution engine, the engine constrains the hub by each - * solution before it calls hub(). See Space::hub() and Space::spoke() - * for details. + * The engine calls hub() on its hub when search starts and when an + * episode ends while search continues: after a solution, at the + * cutoff, and when the search of a spoke ends without a proof. When a + * spoke with SpokeCoverage::Full or SpokeCoverage::Reduced exhausts its + * search space, search ends without a call to hub(). The engine calls + * hub() for a solution in the next call to next(). The engine calls + * spoke() on each spoke it clones from the hub. When \a E is a best + * solution engine, the engine constrains the hub by each solution + * before it calls hub(). As rbs() calls next() only once, hub() is not + * called for the solution it returns. See Space::hub() and + * Space::spoke() for details. * * \ingroup TaskModelSearch */ @@ -1613,9 +1624,12 @@ namespace Gecode { * slices of failures (see Search::Options::slice). * * The stop object in \a o is checked with the statistics of the whole - * portfolio, that is, the sum of the statistics of all assets. With - * parallel assets, these are the statistics that the workers pass to - * their stop objects. When the stop object stops search, end_reason() + * portfolio, that is, the sum of the statistics of all assets. An asset + * contributes the statistics with which it last checked its stop + * object, or its final statistics once it has ended. A parallel asset + * checks its stop object with the statistics of one worker, as any + * parallel engine does, and so contributes those of the worker that + * checked last. When the stop object stops search, end_reason() * returns Search::EndReason::Limit and calling next() again resumes all * assets. * @@ -1628,8 +1642,11 @@ namespace Gecode { * * When the assets are restart-based engines, the portfolio takes * ownership of the cutoff in \a o and gives each asset its own copy - * (see Cutoff::copy()). If the constructor throws an exception, the - * caller keeps the cutoff. + * (see Cutoff::copy()). The exception is a single asset whose spoke has + * SpokeCoverage::Full or SpokeCoverage::Reduced: it runs as the + * restart-based engine itself, which takes the cutoff in \a o and so + * also its random sequence. If the constructor throws an exception, + * the caller keeps the cutoff. * * The spoke of each asset declares its coverage in Space::spoke() (see * SpokeCoverage). When an asset whose spoke has SpokeCoverage::Full or @@ -1648,8 +1665,9 @@ namespace Gecode { * * The engine calls hub() once on its hub with MetaEvent::Start, then * Space::status() on the hub, and then spoke() on the spoke of each - * asset. When the hub had branchers before hub() but a spoke has none - * after spoke(), the engine throws Search::SpokeNoBrancher. See + * asset. When the hub had branchers before hub() but a spoke that has + * not failed has none after spoke(), the engine throws + * Search::SpokeNoBrancher. See * Space::hub() and Space::spoke() for details. * * \ingroup TaskModelSearch @@ -1706,8 +1724,9 @@ namespace Gecode { * * The engine calls hub() once on its hub with MetaEvent::Start, then * Space::status() on the hub, and then spoke() on the spoke of each - * asset. When the hub had branchers before hub() but a spoke has none - * after spoke(), the engine throws Search::SpokeNoBrancher. See + * asset. When the hub had branchers before hub() but a spoke that has + * not failed has none after spoke(), the engine throws + * Search::SpokeNoBrancher. See * Space::hub() and Space::spoke() for details. * * \ingroup TaskModelSearch From 18e9024bf26180a7b72174919bfbd3490cf24c3c Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Wed, 25 Nov 2026 08:02:54 +0100 Subject: [PATCH 27/37] Resume a parallel portfolio after a single limit A portfolio stop with no queued solutions left the stop flag set when next() reported the limit. The next call then reported the limit again without running the assets, so search resumed only on the call after. The flag is now cleared when the limit is reported. --- gecode/search/par/pbs.hpp | 6 ++++-- test/search.cpp | 30 ++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index 1da78e074e..0c62d7418e 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -449,8 +449,10 @@ namespace Gecode { namespace Search { namespace Par { s = nullptr; if (exhausted) end = EndReason::Exhausted; - else if (portfolio_stop.load(std::memory_order_acquire) || (n_active > 0)) - // Stopped by the portfolio stop object, or only parked assets remain + else if (portfolio_stop.exchange(false, std::memory_order_acq_rel) || + (n_active > 0)) + // Stopped by the portfolio stop object, or only parked assets remain, + // the next call resumes the assets end = EndReason::Limit; else // All assets ended without a proof diff --git a/test/search.cpp b/test/search.cpp index 29e17346f0..7f263745bd 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -3865,6 +3865,36 @@ namespace Test { PBSPortfolioStop pbs_portfolio_stop; + /// Portfolio search resumes with the next call after its stop object fired + class PBSPortfolioStopResume : public Base { + /// Whether the assets run again after a single limit + static bool test(unsigned int threads) { + NoSolution root; + Switch s; + s.on = true; + Gecode::Search::Options o; + o.threads = threads; + o.assets = 2; + o.stop = &s; + Gecode::PBS pbs(&root,o); + if ((pbs.next() != nullptr) || (pbs.end_reason() != EndReason::Limit)) + return false; + s.on = false; + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Exhausted); + } + public: + PBSPortfolioStopResume(void) : Base("Search::PBS::PortfolioStopResume") {} + bool run(void) override { + for (unsigned int t : {1U,2U}) + if (!test(t)) + return false; + return true; + } + }; + + PBSPortfolioStopResume pbs_portfolio_stop_resume; + /// An asset stopped by its own stop object is parked while the others continue class PBSParkedAsset : public Base { /// Stop object that always stops From 4c0e82a10e19068b1789d5a019e3e5beee07dca4 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Wed, 25 Nov 2026 09:26:52 +0100 Subject: [PATCH 28/37] Declare the switchable stop of the search tests in every build PortfolioStopResume uses the Switch stop object, which was declared only when the experimental engines are enabled. --- test/search.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/test/search.cpp b/test/search.cpp index 7f263745bd..4068229c2a 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -95,6 +95,17 @@ namespace Test { using Gecode::Search::EndReason; + /// Stop object that stops once it is switched on + class Switch : public Gecode::Search::Stop { + public: + /// Whether search must stop + std::atomic on{false}; + bool stop(const Gecode::Search::Statistics&, + const Gecode::Search::Options&) override { + return on.load(); + } + }; + #ifdef GECODE_HAS_EXPERIMENTAL /// Explicit finite tree with prefix costs, admissible bounds, and ranks class TreeSpace : public Space { @@ -303,17 +314,6 @@ namespace Test { Heuristic astar_test("AStar"); Heuristic cabs_test("CABS"); - /// Stop object that stops once it is switched on - class Switch : public Gecode::Search::Stop { - public: - /// Whether search must stop - std::atomic on{false}; - bool stop(const Gecode::Search::Statistics&, - const Gecode::Search::Options&) override { - return on.load(); - } - }; - /// A heuristic search stays exhausted when its stop object fires later template class E> class HeuristicExhausted : public Base { From a0753c53aeb972668711258dd5905f0905886fca Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Wed, 25 Nov 2026 09:29:14 +0100 Subject: [PATCH 29/37] Keep sequential portfolio assets valid after one ends Removing an asset that ended without a proof assigned to the destroyed slot. The last asset is now copied into the slot as a new object. Once a single asset remains, the slice threshold no longer advances, which wrapped it around from its unlimited value. --- gecode/search/seq/pbs.hpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index cfc9f72742..ece43b6067 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -169,7 +169,9 @@ namespace Gecode { namespace Search { namespace Seq { // The asset ended without a proof, kill it after saving the statistics stat += assets[cur].statistics(); assets[cur].~Asset(); - assets[cur] = assets[--n_assets]; + // Move the last asset into the free slot, it is not destroyed later + if (cur != --n_assets) + new (&assets[cur]) Asset(assets[n_assets]); if (n_assets == 1) // Disable stopping by setting a high limit ssi.l = ULLONG_MAX; @@ -183,8 +185,9 @@ namespace Gecode { namespace Search { namespace Seq { } if (n_sliced + n_parked == n_assets) { n_sliced = 0; - // Increment by one slice - ssi.l += slice; + // Increment by one slice, a single asset has no limit to increment + if (n_assets > 1) + ssi.l += slice; } } // All assets ended without a proof From 0632e34d91cf1bad80c0f3f8aadf391cde8a4c46 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Wed, 25 Nov 2026 09:29:15 +0100 Subject: [PATCH 30/37] Document the limits of Continue, cutoff copies and resuming A Continue keeps the spoke, so constraints that hub() posts reach only later spokes. Copies of a random cutoff use different seeds but need not give different values, and a single non-partial asset keeps the cutoff itself. A failed spoke does not throw SpokeNoBrancher. Resuming after a limit requires lifting the limit first. --- changelog.in | 8 +++++--- docs/gecode-7-migration.md | 16 +++++++++++----- gecode/kernel/core.hpp | 12 ++++++++++-- 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/changelog.in b/changelog.in index 8ef8c34b2a..6fc63ee08e 100755 --- a/changelog.in +++ b/changelog.in @@ -111,7 +111,7 @@ What: change Rank: minor [DESCRIPTION] Throw Search::SpokeNoBrancher when a spoke of portfolio search has no -brancher but the hub had branchers. +brancher but the hub had branchers, unless the spoke failed. [MORE] The default hub() removes all branchers, so a spoke() that forgot to post the branching of its asset returned the unassigned spoke as a solution. @@ -209,8 +209,10 @@ Rank: major Give each restart-based asset of a portfolio its own copy of the cutoff. [MORE] Cutoff has a new pure virtual function copy(), which custom cutoff generators -must implement. Copies of a random cutoff draw different sequences, so the -assets restart at different times. See docs/gecode-7-migration.md. +must implement. Copies of a random cutoff use different seeds, so the assets +can restart at different times. A portfolio with a single asset that does not +declare SpokeCoverage::Partial uses the cutoff itself. See +docs/gecode-7-migration.md. [ENTRY] Module: search diff --git a/docs/gecode-7-migration.md b/docs/gecode-7-migration.md index 131d1b54b1..8053b8cc5a 100644 --- a/docs/gecode-7-migration.md +++ b/docs/gecode-7-migration.md @@ -120,10 +120,13 @@ virtual Gecode::Search::Cutoff* copy(void) const; ``` It returns a copy of the generator in its current state that continues the -sequence on its own. A copy of `Cutoff::rnd()` draws its own random -sequence, so that the assets restart at different times. A portfolio of -restart-based engines, `PBS`, gives each asset its own copy of the -cutoff in its options and deletes the original once the portfolio is built. +sequence on its own. A copy of `Cutoff::rnd()` uses a different seed, so +the assets can restart at different times (unless every value of the range +is the same). A portfolio of restart-based engines, `PBS`, gives +each asset its own copy of the cutoff in its options and deletes the +original once the portfolio is built. A portfolio of a single asset whose +spoke does not declare `SpokeCoverage::Partial` needs no portfolio engine +and passes the cutoff itself to that asset. In Gecode 6.6, the assets drew their values from one shared cutoff sequence. A custom cutoff generator must implement `copy()`. For a generator whose @@ -168,7 +171,10 @@ engine, and calling `next()` again continues the search. Code that used `!stopped()` as a proof, such as reporting optimality, should test for `EndReason::Exhausted`. Code that resumes a search after a limit -should test for `EndReason::Limit`. +should test for `EndReason::Limit`, and first lift the limit: a stop object +that still fires, such as an expired `TimeStop`, stops the search again +right away. Reset the `TimeStop` or raise the limit of a `NodeStop` or +`FailStop` before calling `next()` again. ## Portfolio stop objects see the whole portfolio diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index a640a69fc3..6794608c39 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -1730,7 +1730,14 @@ namespace Gecode { /** * Continue the current episode: after \c Solution, search the same * spoke for the next solution; after \c Limit, resume the same spoke - * with the next cutoff as a fresh budget + * with the next cutoff as a fresh budget. + * + * The spoke is not rebuilt, so constraints that hub() posts reach only + * the spokes of later episodes, and exhausting the spoke proves that + * the hub had no further solution when the spoke was created. In best + * solution search the engine still constrains the spoke with each new + * solution. A hook that restricts the hub in a way that the current + * spoke must respect selects \c Restart instead. */ Continue, /// End the engine: next() returns nullptr with EndReason::Incomplete @@ -2380,7 +2387,8 @@ namespace Gecode { * * The hook may post constraints in the hub and sets what the engine * does next with \a hc.decision() (see MetaDecision for the legal - * decisions and the default). If the hub fails, the engine ends + * decisions and the default). The constraints reach the current spoke + * only with MetaDecision::Restart, which searches a new spoke. If the hub fails, the engine ends * with Search::EndReason::Exhausted whatever the decision: failing * the hub is how a hook declares that no further solution exists. * From 16314f5fb49eb841276f18538d77a65271b2b420 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Wed, 25 Nov 2026 09:35:31 +0100 Subject: [PATCH 31/37] Record the final statistics of a portfolio asset outside the lock An asset of a parallel portfolio that ended without a proof recorded its final statistics while holding the portfolio mutex. When statistics() of its engine threw, fail() took the mutex again and the portfolio deadlocked. The statistics are now recorded before the mutex is taken. --- gecode/search/par/pbs.hpp | 8 ++++-- test/search.cpp | 58 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/gecode/search/par/pbs.hpp b/gecode/search/par/pbs.hpp index 0c62d7418e..0ff6ad3735 100755 --- a/gecode/search/par/pbs.hpp +++ b/gecode/search/par/pbs.hpp @@ -266,6 +266,12 @@ namespace Gecode { namespace Search { namespace Par { // If b is false the report should be repeated (solution was worse) bool b = true; bool wake = false; + if ((s == nullptr) && (asset->end_reason() != EndReason::Limit) && + !pbs_asset_proof(asset->end_reason(),asset->coverage())) + // The asset ended without a proof, its last stop check might not + // include its final work. Record it before taking the lock, as an + // exception from statistics() is reported by fail(), which takes it. + asset->record(); m.acquire(); if (s != nullptr) { try { @@ -303,8 +309,6 @@ namespace Gecode { namespace Search { namespace Par { wake = true; } else { // The asset ended without a proof, move it to inactive - // Its last stop check might not include its final work - asset->record(); unsigned int i=0; while (assets[i] != asset) i++; diff --git a/test/search.cpp b/test/search.cpp index 4068229c2a..23d459a6a5 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -4002,6 +4002,64 @@ namespace Test { PBSAssetException pbs_asset_exception; + /// Exception thrown by the statistics of NoStatistics + class StatisticsFailure {}; + + /// Engine without solutions that cannot report its statistics + class NoStatistics : public Gecode::Search::Engine { + protected: + /// Why next() returns no solution + EndReason r; + public: + NoStatistics(EndReason r0) : r(r0) {} + Gecode::Space* next(void) override { + return nullptr; + } + Gecode::Search::Statistics statistics(void) const override { + throw StatisticsFailure(); + } + EndReason end_reason(void) const override { + return r; + } + }; + + /// Builder for NoStatistics + class NoStatisticsBuilder : public Gecode::Search::Builder { + protected: + /// Why next() of the engine returns no solution + EndReason r; + public: + NoStatisticsBuilder(EndReason r0) + : Gecode::Search::Builder(Gecode::Search::Options::def,false), r(r0) {} + Gecode::Search::Engine* operator ()(Gecode::Space*) const override { + return new NoStatistics(r); + } + }; + + /// An exception from the statistics of an asset that ended is rethrown by next() + class PBSStatisticsException : public Base { + public: + PBSStatisticsException(void) : Base("Search::PBS::StatisticsException") {} + bool run(void) override { + for (unsigned int t : {1U,2U}) { + NoSolution root; + Gecode::SEBs sebs(2); + sebs[0] = new NoStatisticsBuilder(EndReason::Incomplete); + sebs[1] = new NoStatisticsBuilder(EndReason::Incomplete); + Gecode::Search::Options o; + o.threads = t; + Gecode::PBS pbs(&root,sebs,o); + try { + delete pbs.next(); + return false; + } catch (const StatisticsFailure&) {} + } + return true; + } + }; + + PBSStatisticsException pbs_statistics_exception; + /// A copy of a cutoff generator continues its sequence independently class CutoffCopy : public Base { /// Check that a copy of \a c continues as \a c, then delete \a c From 96696b38f3bba48cf76a3383311b23936c8597cf Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Wed, 25 Nov 2026 09:36:16 +0100 Subject: [PATCH 32/37] Collect the statistics of other assets only for a portfolio stop A sequential portfolio summed the statistics of all other assets before each slice, although only the stop object of the portfolio reads them. Without a portfolio stop object the sum is now skipped. --- gecode/search/seq/pbs.hh | 4 ++++ gecode/search/seq/pbs.hpp | 19 +++++++++++++++---- test/search.cpp | 23 +++++++++++++++++++++++ 3 files changed, 42 insertions(+), 4 deletions(-) diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index 49285329cd..6b49f64da1 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -70,6 +70,8 @@ namespace Gecode { namespace Search { namespace Seq { PortfolioStop(Stop* so, Stop* po=nullptr); /// Initialize shared stop information void share(SharedStopInfo* ssi); + /// Whether the portfolio has a stop object + bool portfolio_stop(void) const; /// Return true if portfolio engine must be stopped virtual bool stop(const Statistics& s, const Options& o); }; @@ -102,6 +104,8 @@ namespace Gecode { namespace Search { namespace Seq { Statistics statistics(void) const; /// Return why the last call to next() of the asset returned no solution EndReason end_reason(void) const; + /// Whether the portfolio has a stop object + bool portfolio_stop(void) const; /// Constrain with better solution \a b void constrain(const Space& b); /// Park the asset after its stop object stopped it diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index ece43b6067..38c5c1a8a6 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -43,6 +43,10 @@ namespace Gecode { namespace Search { namespace Seq { PortfolioStop::share(SharedStopInfo* ssi0) { ssi = ssi0; } + forceinline bool + PortfolioStop::portfolio_stop(void) const { + return po != nullptr; + } forceinline @@ -70,6 +74,10 @@ namespace Gecode { namespace Search { namespace Seq { Asset::end_reason(void) const { return engine->end_reason(); } + forceinline bool + Asset::portfolio_stop(void) const { + return static_cast(stop)->portfolio_stop(); + } forceinline void Asset::constrain(const Space& b) { engine->constrain(b); @@ -129,10 +137,13 @@ namespace Gecode { namespace Search { namespace Seq { continue; } ssi.cause = PortfolioStopCause::None; - ssi.others = stat; - for (unsigned int i=0U; i pbs(&root,sebs,o); + try { + return (pbs.next() == nullptr) && + (pbs.end_reason() == EndReason::Limit); + } catch (const StatisticsFailure&) { + return false; + } + } + }; + + PBSNoStopStatistics pbs_no_stop_statistics; + /// A copy of a cutoff generator continues its sequence independently class CutoffCopy : public Base { /// Check that a copy of \a c continues as \a c, then delete \a c From eb12d3c40bfde7cdc5000f161b4cfddc21c6ca63 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Wed, 25 Nov 2026 09:40:00 +0100 Subject: [PATCH 33/37] Document which statistics the assets of a sequential portfolio contribute The stop object of a sequential portfolio sees the current statistics of the assets that are paused, for a parallel asset those of all its workers, not the statistics of their last stop check. --- gecode/search.hh | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/gecode/search.hh b/gecode/search.hh index a7c2e917a1..bc0c7c35ac 100755 --- a/gecode/search.hh +++ b/gecode/search.hh @@ -1624,14 +1624,16 @@ namespace Gecode { * slices of failures (see Search::Options::slice). * * The stop object in \a o is checked with the statistics of the whole - * portfolio, that is, the sum of the statistics of all assets. An asset - * contributes the statistics with which it last checked its stop - * object, or its final statistics once it has ended. A parallel asset - * checks its stop object with the statistics of one worker, as any - * parallel engine does, and so contributes those of the worker that - * checked last. When the stop object stops search, end_reason() - * returns Search::EndReason::Limit and calling next() again resumes all - * assets. + * portfolio, that is, the sum of the statistics of all assets. The + * asset that checks contributes the statistics it checks with, which + * for a parallel asset are those of one worker, as for any parallel + * engine. With one thread, every other asset is paused and contributes + * its current statistics, for a parallel asset those of all its + * workers. With more threads, every other asset contributes the + * statistics with which it last checked its stop object, or its final + * statistics once it has ended. When the stop object stops search, + * end_reason() returns Search::EndReason::Limit and calling next() + * again resumes all assets. * * For best-solution assets, a solution replaces the incumbent only if * Space::compare reports SpaceComparison::Better. From 55abe96bba18c5b81974d948f2b8e610cd0b5583 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Wed, 25 Nov 2026 09:44:08 +0100 Subject: [PATCH 34/37] Guard the shared stop information of a sequential portfolio A worker of a parallel asset can check its stop object after next() of the asset has returned, while the portfolio already writes the statistics of the other assets and the failure limit for the next asset. The statistics are now copied under a mutex and the failure limit is atomic. --- gecode/search/seq/pbs.cpp | 13 ++++++++--- gecode/search/seq/pbs.hh | 12 ++++++++-- gecode/search/seq/pbs.hpp | 6 +++-- test/search.cpp | 49 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 73 insertions(+), 7 deletions(-) diff --git a/gecode/search/seq/pbs.cpp b/gecode/search/seq/pbs.cpp index 4ed990a475..59bac5b394 100644 --- a/gecode/search/seq/pbs.cpp +++ b/gecode/search/seq/pbs.cpp @@ -37,9 +37,16 @@ namespace Gecode { namespace Search { namespace Seq { bool PortfolioStop::stop(const Statistics& s, const Options& o) { - if ((po != nullptr) && po->stop(ssi->others + s,o)) { - pbs_record_cause(ssi->cause,PortfolioStopCause::Portfolio); - return true; + if (po != nullptr) { + Statistics others; + { + Support::Lock lock(ssi->m); + others = ssi->others; + } + if (po->stop(others + s,o)) { + pbs_record_cause(ssi->cause,PortfolioStopCause::Portfolio); + return true; + } } if ((so != nullptr) && so->stop(s,o)) { pbs_record_cause(ssi->cause,PortfolioStopCause::Asset); diff --git a/gecode/search/seq/pbs.hh b/gecode/search/seq/pbs.hh index 6b49f64da1..4201b5a710 100644 --- a/gecode/search/seq/pbs.hh +++ b/gecode/search/seq/pbs.hh @@ -39,13 +39,21 @@ namespace Gecode { namespace Search { namespace Seq { - /// Shared stop information + /** + * \brief Shared stop information + * + * A worker of a parallel asset can check its stop object after next() + * of the asset has returned, while the portfolio already prepares the + * next asset. + */ class SharedStopInfo { public: /// Which stop object stopped the running asset, its workers can run in parallel std::atomic cause; /// The current failure limit, incremented for each slice - unsigned long long int l; + std::atomic l; + /// Mutex protecting others + Support::Mutex m; /// Statistics of the portfolio except for the running asset Statistics others; }; diff --git a/gecode/search/seq/pbs.hpp b/gecode/search/seq/pbs.hpp index 38c5c1a8a6..d49339d42a 100644 --- a/gecode/search/seq/pbs.hpp +++ b/gecode/search/seq/pbs.hpp @@ -139,10 +139,12 @@ namespace Gecode { namespace Search { namespace Seq { ssi.cause = PortfolioStopCause::None; // Only the stop object of the portfolio uses the other assets if (assets[cur].portfolio_stop()) { - ssi.others = stat; + Statistics others(stat); for (unsigned int i=0U; i(a); + sebs[1] = Gecode::dfs(a); + Gecode::Search::Options o; + o.threads = 1; + o.slice = 1; + o.stop = &n; + Gecode::PBS pbs(&root,sebs,o); + // Each asset finds each of the 720 solutions + unsigned int solutions = 0; + while (Distinct* s = pbs.next()) { + delete s; + solutions++; + } + return (pbs.end_reason() == EndReason::Exhausted) && + (solutions >= 720U) && (solutions <= 2U * 720U); + } + }; + + PBSParallelAssets pbs_parallel_assets; + /// An asset stopped by its own stop object is parked while the others continue class PBSParkedAsset : public Base { /// Stop object that always stops From bdab736e98da90821a09c8ebb41e8b50c03d2d51 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Wed, 25 Nov 2026 09:32:34 +0100 Subject: [PATCH 35/37] Report CABS exhausted when it stops after its last solution When the last solution left no work behind, for example a solved root, a stop before the next call to next() made CABS report a limit, although resuming finds nothing. Sequential CABS now recognizes that no node, layer entry, candidate, or improving discarded entry remains before it checks the stop object. The parallel frontier shared by CABS and A* checks the same before it resumes and when its workers stop. --- gecode/search/astar.cpp | 3 +++ gecode/search/cabs.cpp | 9 +++++++ gecode/search/par/frontier.cpp | 9 ++++++- gecode/search/par/frontier.hh | 4 +++ test/search.cpp | 49 ++++++++++++++++++++++++++++++++++ 5 files changed, 73 insertions(+), 1 deletion(-) diff --git a/gecode/search/astar.cpp b/gecode/search/astar.cpp index cb2d36624a..301a67397e 100644 --- a/gecode/search/astar.cpp +++ b/gecode/search/astar.cpp @@ -66,6 +66,9 @@ namespace Gecode { namespace Search { namespace Par { bool advance(void) override { return false; } + bool can_advance(void) const override { + return false; + } void clear(void) override { queue.clear(); } diff --git a/gecode/search/cabs.cpp b/gecode/search/cabs.cpp index 2b3b6648bb..e9e6130cbd 100644 --- a/gecode/search/cabs.cpp +++ b/gecode/search/cabs.cpp @@ -103,6 +103,9 @@ namespace Gecode { namespace Search { namespace Par { void started(const Space& r) override { root.reset(r.clone()); } + bool can_advance(void) const override { + return !candidates.empty() || candidates.improving(best); + } public: /// Initialize for space \a s with options \a o CABS(Space* s, const Options& o) @@ -240,6 +243,12 @@ namespace Gecode { namespace Search { namespace Seq { if (_exhausted) return nullptr; while (true) { + // An exhausted search is complete, even when a limit has been reached + if (!expansion && layer.empty() && candidates.empty() && + !candidates.improving(best)) { + _exhausted = true; + return nullptr; + } if (stop_seq(opt)) return nullptr; if (!expansion) { diff --git a/gecode/search/par/frontier.cpp b/gecode/search/par/frontier.cpp index a16f4080fe..ca0ad8945c 100644 --- a/gecode/search/par/frontier.cpp +++ b/gecode/search/par/frontier.cpp @@ -165,6 +165,11 @@ namespace Gecode { namespace Search { namespace Par { running = false; } + bool + Frontier::drained(void) const { + return (n_pending == 0) && !open() && (active == 0) && !can_advance(); + } + void Frontier::work(unsigned int id) { // The leased task and the incumbent used for constraining its children @@ -343,6 +348,8 @@ namespace Gecode { namespace Search { namespace Par { return nullptr; } // An exhausted search is complete, even when a limit has been reached + if (drained()) + _exhausted = true; if (_exhausted) { _stopped = false; end = EndReason::Exhausted; @@ -364,7 +371,7 @@ namespace Gecode { namespace Search { namespace Par { end = EndReason::NotEnded; else if (_limited) end = EndReason::Incomplete; - else if (_exhausted) + else if (_exhausted || drained()) end = EndReason::Exhausted; else end = _stopped ? EndReason::Limit : EndReason::Exhausted; diff --git a/gecode/search/par/frontier.hh b/gecode/search/par/frontier.hh index ebb0ee6bfe..a2810783a4 100644 --- a/gecode/search/par/frontier.hh +++ b/gecode/search/par/frontier.hh @@ -127,6 +127,8 @@ namespace Gecode { namespace Search { namespace Par { virtual void submit(const Entry& e, bool leased) = 0; /// Called when all work is done, return whether there is new work virtual bool advance(void) = 0; + /// Whether advance() would find new work, without changing anything + virtual bool can_advance(void) const = 0; /// Delete all open nodes virtual void clear(void) = 0; /// Called with the root \a r when search starts @@ -157,6 +159,8 @@ namespace Gecode { namespace Search { namespace Par { bool enabled(unsigned int id); /// Run worker \a id void work(unsigned int id); + /// Whether no work is left (called with the mutex held) + bool drained(void) const; public: /// Destructor ~Frontier(void) override; diff --git a/test/search.cpp b/test/search.cpp index 5e31339b89..26399253c3 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -353,6 +353,55 @@ namespace Test { HeuristicExhausted astar_exhausted("AStar"); HeuristicExhausted cabs_exhausted("CABS"); + /// A heuristic search that has no work left after its last solution is + /// exhausted when its stop object fires before the next call + template class E> + class HeuristicExhaustedAfterSolution : public Base { + public: + HeuristicExhaustedAfterSolution(const std::string& name) + : Base("Search::"+name+"::ExhaustedAfterSolution") {} + bool run(void) override { + // A solved root, and a root whose only child is a solution + const std::vector graphs = { + {{0,0,0,0,{}}}, + {{0,0,0,1,{1}}, {1,1,0,1,{}}} + }; + for (const TreeSpace::Graph& graph : graphs) + for (unsigned int threads : {1U,2U}) { +#ifndef GECODE_HAS_THREADS + if (threads > 1U) continue; +#endif + TreeSpace root(std::make_shared(graph), + false); + Gecode::Search::HeuristicGuidance g = + TreeSpace::guidance(false,false,false,false); + Switch stop; + Gecode::Search::Options o; + o.threads = threads; + o.guidance = &g; + o.stop = &stop; + E e(&root,o); + TreeSpace* s = e.next(); + if (s == nullptr) + return false; + delete s; + stop.on = true; + if (TreeSpace* t = e.next()) { + delete t; + return false; + } + if (e.end_reason() != EndReason::Exhausted) + return false; + } + return true; + } + }; + + HeuristicExhaustedAfterSolution + astar_exhausted_after_solution("AStar"); + HeuristicExhaustedAfterSolution + cabs_exhausted_after_solution("CABS"); + /// Portfolio of BAB, A*, and CABS assets class HeuristicPortfolio : public Base { /// Stop object that never stops but takes some time From f8f9ff5b53c419515bd1318bbd3dadbc9e858daf Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Wed, 25 Nov 2026 09:39:02 +0100 Subject: [PATCH 36/37] Leave the hub constraint of the PBS test to propagation The hub of the portfolio test posted c <= 1 as a domain update, so the hub stayed stable and the test passed even when PBS did not propagate the hub before cloning the spokes. The hub now posts a constraint that only propagation enforces, and the test checks that the hub is not stable when hub() returns. --- test/search.cpp | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/test/search.cpp b/test/search.cpp index 26399253c3..fef40309a3 100644 --- a/test/search.cpp +++ b/test/search.cpp @@ -4310,7 +4310,7 @@ namespace Test { FailAtSolution, ///< hub() fails at Solution ContinueAtLimit, ///< hub() continues at Limit EmptyHub, ///< hub() does nothing - BoundInHub, ///< hub() posts c <= 1 at Start and keeps the branchers + BoundInHub, ///< hub() leaves c <= 1 to propagation at Start, keeps the branchers Alternate, ///< Episodes alternate between a solution and the cutoff }; @@ -4322,6 +4322,8 @@ namespace Test { std::vector > spoke; /// Number of spaces alive std::atomic live{0}; + /// Number of hub() calls that returned with the hub not stable + std::atomic unstable{0U}; }; /// Space whose hooks follow a Protocol @@ -4406,7 +4408,12 @@ namespace Test { return; case Protocol::BoundInHub: if (hc.event() == MetaEvent::Start) { - rel(*this,c,IRT_LQ,1); + // Only propagation enforces c <= 1, posting does not prune c + BoolVar b(*this,0,1); + rel(*this,c,IRT_LQ,1,Reify(b,RM_IMP)); + rel(*this,b,IRT_EQ,1); + if (!stable()) + log->unstable++; return; } break; @@ -4704,10 +4711,12 @@ namespace Test { Gecode::Search::Options o; o.assets = 2; o.threads = t; + unsigned int unstable = log.unstable; Gecode::PBS pbs(m,o); delete m; ProtocolSpace* s = pbs.next(); - const bool ok = (s != nullptr) && (s->c.val() == 1); + const bool ok = (s != nullptr) && (s->c.val() == 1) && + (log.unstable == unstable+1U); delete s; if (!ok) return false; @@ -4719,10 +4728,12 @@ namespace Test { SEBs assets(2); for (int i=0; i<2; i++) assets[i] = Gecode::dfs(o); + unsigned int unstable = log.unstable; Gecode::PBS pbs(m,assets,o); delete m; ProtocolSpace* s = pbs.next(); - const bool ok = (s != nullptr) && (s->c.val() == 1); + const bool ok = (s != nullptr) && (s->c.val() == 1) && + (log.unstable == unstable+1U); delete s; if (!ok) return false; From f1196fb66da58dd191e1826257e9f785f7d0a8ff Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Wed, 25 Nov 2026 10:09:42 +0100 Subject: [PATCH 37/37] Say which solution a meta-search hook sees as the last one In a portfolio, a better solution from another asset replaces the solution of the asset itself. --- gecode/kernel/core.hpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 6794608c39..c8a0fdc1b9 100755 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -1830,9 +1830,11 @@ namespace Gecode { /// Return the number of assets of a portfolio (one for RBS) unsigned int assets(void) const; /** - * \brief Return the most recent solution, or nullptr if none + * \brief Return the best solution the engine knows, or nullptr if none * - * The engine owns the solution, and the pointer is valid only while + * This is the most recent solution of the engine, or a better one that + * constrain() passed to the engine since, for example from another + * asset of a portfolio. The engine owns the solution, and the pointer is valid only while * the hook runs: clone the solution to keep it. */ const Space* last(void) const;