From bb4d8a013cce57fdb30e98f7a670e70b11d018ef Mon Sep 17 00:00:00 2001 From: Joseph Wood Date: Fri, 4 Dec 2026 00:24:17 -0500 Subject: [PATCH] fix: guard parallel polynomial scheduling estimates Stop estimating work once the relation target is reached or exceeded. Validate estimates and duration arithmetic, clearing both outputs for serial fallback on invalid or empty batches. Preserve integer-clock truncation and existing timing thresholds. Add native boundary regressions and serial/parallel factorization checks. --- .github/development/DEFERRED_ISSUES.md | 90 ++++++- .../development/test-polynomial-scheduling.R | 255 ++++++++++++++++++ .github/development/testing.md | 50 ++++ NEWS.md | 1 + inst/NEWS.Rd | 3 + src/Polynomial.cpp | 102 ++++++- tests/testthat/testQuadraticSieve.R | 14 + 7 files changed, 489 insertions(+), 26 deletions(-) create mode 100644 .github/development/test-polynomial-scheduling.R diff --git a/.github/development/DEFERRED_ISSUES.md b/.github/development/DEFERRED_ISSUES.md index b929956..496bd46 100644 --- a/.github/development/DEFERRED_ISSUES.md +++ b/.github/development/DEFERRED_ISSUES.md @@ -293,7 +293,7 @@ Next step: Include the fix in the next release and record its version here. ## Empty inputs return an uninitialized integer -Status: Implemented and tested locally; not yet merged or released; separate from [issue #9](https://github.com/jwood000/RcppBigIntAlgos/issues/9) +Status: Resolved in main; merged in [PR #18](https://github.com/jwood000/RcppBigIntAlgos/pull/18) (`7171778`); not yet released; separate from [issue #9](https://github.com/jwood000/RcppBigIntAlgos/issues/9) Priority: Medium Evidence: Source inspection and failing-before/passing-after public-API regressions @@ -343,26 +343,90 @@ test review found no correctness defects. No sanitizers were run, and no CI workflows or dependencies changed. This validation does not include `--as-cran` or cross-platform checks. -Next step: Review and merge the fix, then record its merge and release here. +Next step: Include the fix in the next release and record its version here. ## Parallel polynomial scheduling estimates work after completion -Status: Open +Status: Implemented and tested locally; not yet merged or released Priority: Medium -Evidence: Isolated arithmetic reproduction under Clang's float-cast-overflow sanitizer +Evidence: Source review, guarded native baseline comparison, and serial/parallel public-API checks `SetThreadsPolys()` in [Polynomial.cpp](../../src/Polynomial.cpp) is called after merging a batch, before rechecking whether enough relations have been collected. For `currLim = 2010`, `SaPThresh = 2000`, and `nPolys = 1000`, its -remaining-work estimate is approximately `-3.65559`. Converting that value -to `std::size_t` is undefined; the isolated sanitizer check reported it. -This was not a full-package sanitizer run or an observed user-facing crash. - -Next step: Handle a reached/exceeded target before estimating remaining work. -Keep the result consistent with subsequent serial collection and solution -search. Check values below, at, and above the target, including a large -overshoot; avoid invalid logarithms and negative/NaN conversions. Remaining -work should produce a bounded batch or an explicit serial fallback. +old remaining-work estimate was approximately `-3.65559`. Converting that +value to `std::size_t` is undefined. The original investigation reproduced +this arithmetic with Clang's float-cast-overflow sanitizer; no sanitizers are +used for the current fix. A public-API crash has not been established. + +The helper now returns no parallel work before evaluating the estimate when +the target is reached or exceeded. It checks floating estimates before +conversion and bounds duration arithmetic before performing it. The original +integer-clock multiplication/division order, tick truncation, and 15/30-second +comparisons are retained. Guards use chrono's actual promoted representation, +which can be unsigned even when the clock itself has a signed representation. +Both duration products and common-period conversions are checked. A positive +elapsed duration whose average truncates to zero ticks still gets the original +full batch; a time limit yielding zero polynomials instead takes the existing +serial fallback. + +Boundary regressions specifically protect old valid schedules that a +floating-seconds rewrite changed: three workers with 25 polynomials each at +the 30-second boundary plus 100 nanoseconds; eight workers with one polynomial +each at the one-polynomial limit plus one nanosecond; and an exact 30-second +average with 25 workers where floating-point rounding would force serial +collection. Neighboring tick-crossing cases verify the original transitions. + +Both scheduling outputs are cleared on fallback. Zero polynomial counts, +insufficient worker limits, invalid timing measurements, and unrepresentable +estimates also take that path; these are defensive helper boundaries, not +additional public-API failures. The surrounding parallel/serial loops, the +ten-relation threshold increment, and the strict solution-readiness comparison +remain unchanged. Reaching the current target stops further parallel batches +without prematurely declaring solution readiness. + +The development-only [native runner](test-polynomial-scheduling.R) passes all +50 cases with the production helper extracted verbatim. Cases cover target +completion and overshoot, invalid/range-limited estimates, worker limits, +integer timing boundaries, duration overflow guards, common-period conversion, +and nonempty bounded batches. Against baseline `7171778`, an instrumented +comparison fails 21 of 43 cases and passes 22. It replaces +only the old remaining-count declaration with a checked conversion wrapper; +five cases are stopped before an invalid conversion could execute. Other +failures expose stale output values or invalid scheduling decisions under the +fallback contract. Seven synthetic cases run only against the fixed +helper. No original undefined conversion is executed by this comparison, and +it is not a public-API crash reproduction. The runner remains excluded from +the package archive and CI; commands and prerequisites are in +[testing.md](testing.md). + +The earlier floating-seconds implementation fails five of these 50 cases: +four integer-clock scheduling regressions and a fine-period conversion guard. +A separate native comparison of extracted helpers matches all 166,048 safe, +nonempty original parallel schedules with positive elapsed time. This includes +55,724 zero-tick averages, nanosecond/millisecond/second clocks, unsigned and +fractional-period clocks, and adjacent timing boundaries. Unsafe, inactive, +and zero-work original schedules are excluded before comparison. This checks +scheduling decisions; it is not an end-to-end performance benchmark. + +Four new package expectations in +[testQuadraticSieve.R](../../tests/testthat/testQuadraticSieve.R) check exact +sorted factors and reconstruction of the fixed 162-bit semiprime +`2923003274661805836407421649242809468366377451741` with one and two threads. +Its prime factors are `1208925819614629174706189` and +`2417851639229258349412369`. Baseline statistics confirm MPQS is reached and +the two-thread run enters parallel batches. These output checks pass both +before and after the fix; the native cases establish the boundary regression. + +A fresh source-archive `R CMD check --no-manual` finishes with `Status: OK`. +All 500 expectations across 34 blocks pass with no failures, warnings, or +skips, using R 4.6.1 / Apple Clang 17 on macOS arm64. Repository indexes were +unavailable; installed dependencies were sufficient. Independent source and +native-runner review found no actionable defects. No sanitizers were run, and +no CI workflows or package dependencies changed. This validation does not +include `--as-cran` or cross-platform checks. + +Next step: Review and merge the fix, then record its merge and release here. ## Relation storage retains unused polynomials and zero-parity columns diff --git a/.github/development/test-polynomial-scheduling.R b/.github/development/test-polynomial-scheduling.R new file mode 100644 index 0000000..4fe7854 --- /dev/null +++ b/.github/development/test-polynomial-scheduling.R @@ -0,0 +1,255 @@ +# Manual development checks; not invoked by R CMD check or CI. +# Rscript --vanilla .github/development/test-polynomial-scheduling.R [source-root] +# To inspect the old implementation without performing its invalid conversion: +# Rscript --vanilla .github/development/test-polynomial-scheduling.R /path/to/baseline --checked-baseline + +main <- function(root, checkedBaseline) { + root <- normalizePath(root, winslash = "/", mustWork = TRUE) + source <- readLines(file.path(root, "src", "Polynomial.cpp")) + first <- grep("^void SetThreadsPolys\\(", source) + after <- grep("^void Polynomial::FactorParallel\\(", source) + minimum <- grep("^constexpr std::size_t MinPolysPerThrd =", source, + value = TRUE) + stopifnot(length(first) == 1L, length(after) == 1L, after > first, + length(minimum) == 1L, + source[first - 1L] == "template ") + helper <- source[seq.int(first - 1L, after - 1L)] + stats <- normalizePath(file.path(root, "inst", "include", "StatsUtils.h"), + winslash = "/", mustWork = TRUE) + + declaration <- " const std::size_t nPolysRemaining = percentRemaining *" + if (!checkedBaseline && any(helper == declaration)) { + stop("Source contains the original unchecked estimate conversion; ", + "rerun with --checked-baseline.", call. = FALSE) + } + if (checkedBaseline) { + # Only the original implicit estimate conversion is instrumented. + # The constructor rejects values outside the C++ conversion range + # before casting. No sanitizer or copied scheduling algorithm is used. + stopifnot(sum(helper == declaration) == 1L) + helper[helper == declaration] <- sub( + "std::size_t", "CheckedPolyCount", declaration, fixed = TRUE + ) + cat("Baseline mode: instrumenting only the remaining-count conversion.\n") + } else { + cat("Fixed-source mode: compiling the production helper verbatim.\n") + } + + support <- ' +class CheckedPolyCount { + std::size_t value_; +public: + CheckedPolyCount(double value) { + // Truncation of a value in (-1, 0) to unsigned zero is valid C++. + const double upper = std::ldexp(1.0, + std::numeric_limits::digits); + if (!std::isfinite(value) || value <= -1.0 || value >= upper) { + throw std::runtime_error("guarded baseline: invalid size_t conversion prevented"); + } + value_ = static_cast(value); + } + operator std::size_t() const { return value_; } +}; + +std::size_t parse_count(const std::string& text) { + const auto limit = std::numeric_limits::max(); + if (text == "max") return limit; + if (text == "max-1") return limit - 1; + const auto value = std::stoull(text); + if (value > limit) throw std::runtime_error("test count exceeds size_t"); + return static_cast(value); +} +' + wrapper <- ' +[[cpp11::register]] +cpp11::writable::list run_polynomial_schedule( + std::string current, std::string target, std::string workers, + std::string processed, std::string elapsed, bool floating, std::string period +) { + const auto currLim = parse_count(current); + const auto threshold = parse_count(target); + const auto maximum = parse_count(workers); + const auto nPolys = parse_count(processed); + // Sentinels ensure every fallback clears both outputs. + std::size_t nThreads = 17; + std::size_t polysPerThread = 23; + std::string failure; + std::fenv_t oldEnvironment; + std::fegetenv(&oldEnvironment); + std::feclearexcept(FE_ALL_EXCEPT); + try { + if (floating) { + const double seconds = elapsed == "denorm_min" ? + std::numeric_limits::denorm_min() : std::stod(elapsed); + SetThreadsPolys(currLim, threshold, nThreads, maximum, + polysPerThread, nPolys, std::chrono::duration(seconds)); + } else { + using Nanoseconds = std::chrono::nanoseconds; + const auto ticks = elapsed == "max" ? + std::numeric_limits::max() : std::stoll(elapsed); + if (period == "three-halves") { + using CoarseTicks = std::chrono::duration< + Nanoseconds::rep, std::ratio<3, 2>>; + SetThreadsPolys(currLim, threshold, nThreads, maximum, + polysPerThread, nPolys, CoarseTicks(ticks)); + } else if (period == "attoseconds") { + using FineTicks = std::chrono::duration; + SetThreadsPolys(currLim, threshold, nThreads, maximum, + polysPerThread, nPolys, FineTicks(ticks)); + } else if (period == "nanoseconds") { + SetThreadsPolys(currLim, threshold, nThreads, maximum, + polysPerThread, nPolys, Nanoseconds(ticks)); + } else { + throw std::runtime_error("unknown test clock period"); + } + } + } catch (const std::exception& e) { + failure = e.what(); + } + const int invalid = std::fetestexcept(FE_INVALID | FE_DIVBYZERO); + std::fesetenv(&oldEnvironment); + const bool bounded = nThreads <= maximum && + ((nThreads == 0 && polysPerThread == 0) || + (nThreads >= 2 && polysPerThread > 0 && + polysPerThread <= std::numeric_limits::max() / nThreads)); + using namespace cpp11::literals; + return {"threads"_nm = std::to_string(nThreads), + "polys"_nm = std::to_string(polysPerThread), "bounded"_nm = bounded, + "invalid"_nm = invalid, "error"_nm = failure}; +} +' + code <- paste(c( + '#include ', '#include ', '#include ', + '#include ', '#include ', '#include ', + '#include ', '#include ', '#include ', + '#include ', + sprintf('#include %s', encodeString(stats, quote = '"')), + minimum, support, helper, wrapper + ), collapse = "\n") + native <- new.env(parent = globalenv()) + cpp11::cpp_source(code = code, env = native, cxx_std = "CXX14") + + case <- function(label, current = 500L, target = 2000L, workers = 8L, + processed = 1000L, elapsed = "1000000000", + floating = FALSE, threads = "0", polys = "0", + baseline = TRUE, period = "nanoseconds") { + list(label = label, current = current, target = target, + workers = workers, processed = processed, elapsed = elapsed, + floating = floating, threads = threads, polys = polys, + baseline = baseline, period = period) + } + cases <- list( + case("uncapped batch", threads = "8", polys = "127"), + case("15-second cap", elapsed = "20000000000", threads = "8", polys = "93"), + case("30-second cap", elapsed = "60000000000", threads = "8", polys = "62"), + case("fewer useful workers", current = 1500L, threads = "3", polys = "50"), + case("requested worker limit", workers = 2L, threads = "2", polys = "509"), + case("no relations yet", current = 0L, processed = 40L, + threads = "8", polys = "150"), + case("just below target with useful history", current = 1999L, + processed = 1000000L, threads = "8", polys = "45"), + case("just below target without a useful batch", current = 1999L), + case("small remaining batch", current = 1900L), + case("only one useful worker", current = 1750L), + case("target reached", current = 2000L), + case("target exceeded by one", current = 2001L), + case("reported overshoot", current = 2010L), + case("logarithm boundary overshoot", current = 2400L), + case("large overshoot", current = 100000L), + case("zero target", current = 0L, target = 0L), + case("maximum counts reached", current = "max", target = "max"), + case("rounded completion", current = "max-1", target = "max"), + case("no processed polynomials", processed = 0L), + case("zero worker limit", workers = 0L), + case("one worker limit", workers = 1L), + case("zero elapsed time", elapsed = "0"), + case("negative elapsed time", elapsed = "-1", floating = TRUE), + case("infinite elapsed time", elapsed = "Inf", floating = TRUE), + case("NaN elapsed time", elapsed = "NaN", floating = TRUE), + case("underflowing per-polynomial time", elapsed = "denorm_min", + floating = TRUE, baseline = FALSE), + case("maximum integral duration", elapsed = "max", baseline = FALSE), + case("worker-scaled duration overflows its chrono representation", + elapsed = "2305843009213693952", baseline = FALSE), + case("full-batch duration overflows its chrono representation", + current = 0L, processed = 40L, elapsed = "10000000000000", + baseline = FALSE), + case("worker-scaled duration fits the promoted unsigned representation", + processed = 1000000000L, elapsed = "2000000000000000000", + threads = "8", polys = "1"), + case("coarse clock preserves duration comparison and division", + elapsed = "1000", period = "three-halves", threads = "8", polys = "2"), + case("clock conversion overflows the common comparison period", + workers = 2L, elapsed = "8000000000000000000", + period = "three-halves", baseline = FALSE), + case("time budget conversion overflows the common comparison period", + period = "attoseconds", baseline = FALSE), + case("one polynomial exceeds time budget", elapsed = "5000000000000"), + case("one polynomial fits time budget", elapsed = "3750000000000", + threads = "8", polys = "1"), + case("one polynomial still fits before the next integer tick", + elapsed = "3750000000001", threads = "8", polys = "1"), + case("one polynomial exceeds the budget at the next integer tick", + elapsed = "3750000000125"), + case("integer division retains one polynomial per worker", + current = 1L, processed = 57L, workers = 25L, + elapsed = "68400000000", threads = "25", polys = "1"), + case("estimate outside size_t range", processed = "max"), + case("large safe estimate", current = 1999L, processed = "max", + threads = "8", polys = NA_character_, baseline = FALSE), + case("sub-tick average time", elapsed = "1", threads = "8", polys = "127"), + case("exact 15-second boundary", current = 1500L, elapsed = "100000000000", + threads = "3", polys = "50"), + case("15-second boundary before the next integer tick", current = 1500L, + elapsed = "100000000100", threads = "3", polys = "50"), + case("below 15-second boundary", current = 1500L, elapsed = "99000000000", + threads = "3", polys = "50"), + case("above 15-second boundary", current = 1500L, elapsed = "101000000000", + threads = "3", polys = "49"), + case("exact 30-second boundary", current = 1500L, elapsed = "200000000000", + threads = "3", polys = "25"), + case("30-second boundary before the next integer tick", current = 1500L, + elapsed = "200000000100", threads = "3", polys = "25"), + case("30-second boundary at the next integer tick", current = 1500L, + elapsed = "200000000334", threads = "3", polys = "49"), + case("below 30-second boundary", current = 1500L, elapsed = "199000000000", + threads = "3", polys = "25"), + case("above 30-second boundary", current = 1500L, elapsed = "201000000000", + threads = "3", polys = "49") + ) + if (checkedBaseline) { + # Fixed-only cases include arithmetic hazards beyond the guarded + # estimate conversion; do not run those against the original helper. + cases <- Filter(function(x) x$baseline, cases) + } + failures <- character(0) + for (input in cases) { + tryCatch({ + asCount <- function(x) format(x, scientific = FALSE, trim = TRUE) + result <- native$run_polynomial_schedule( + asCount(input$current), asCount(input$target), asCount(input$workers), + asCount(input$processed), input$elapsed, input$floating, input$period + ) + if (nzchar(result$error)) stop(result$error, call. = FALSE) + stopifnot(result$invalid == 0L, isTRUE(result$bounded), + identical(result$threads, input$threads)) + if (!is.na(input$polys)) { + stopifnot(identical(result$polys, input$polys)) + } + }, error = function(e) { + failures <<- c(failures, paste(input$label, conditionMessage(e), sep = ": ")) + }) + } + if (length(failures)) { + writeLines(failures, stderr()) + stop(sprintf("%d of %d native scheduling cases failed.", + length(failures), length(cases)), call. = FALSE) + } + cat(sprintf("All %d native polynomial scheduling cases passed.\n", length(cases))) +} + +args <- commandArgs(trailingOnly = TRUE) +checkedBaseline <- "--checked-baseline" %in% args +args <- args[args != "--checked-baseline"] +stopifnot(length(args) <= 1L) +main(if (length(args)) args[[1L]] else ".", checkedBaseline) diff --git a/.github/development/testing.md b/.github/development/testing.md index 3d25e70..9e4cae6 100644 --- a/.github/development/testing.md +++ b/.github/development/testing.md @@ -172,6 +172,56 @@ Rscript .github/development/test-constrained-rho.R /path/to/baseline Keep these native fixtures distinct from public API reproductions. Public entry points remove small factors first and do not expose the helper's limit. +## Parallel polynomial scheduling native regression checks + +Run the development-only scheduler checks from the repository root: + +```sh +Rscript --vanilla .github/development/test-polynomial-scheduling.R +``` + +The [runner](test-polynomial-scheduling.R) extracts `SetThreadsPolys()` +verbatim from the current source, along with its minimum-polynomial constant, +and includes the production timing constants from `StatsUtils.h`. Extraction +anchors must remain unique. It compiles a temporary wrapper with +`cpp11::cpp_source()` using the manual development prerequisites listed above. +It adds no entry point to the package and is not invoked by CI or `R CMD check`. + +The 50 cases cover completion, overshoot, logarithm-domain boundaries, nearly +equal large counts, estimate range limits, worker limits, invalid timing, and +the 15/30-second batch caps. Exact boundaries and neighboring integer ticks +protect the old clock truncation, including the last polynomial that fits in +the time budget and the 15/30-second budget transitions. Arithmetic cases +cover both duration products, unsigned promotion, valid zero-tick averages, +and common-period conversion bounds with synthetic coarse/fine clocks. +Each result must either clear both scheduling outputs for +serial fallback or produce a nonempty parallel batch with a bounded product. +Floating invalid-operation and division-by-zero flags are also checked; no +sanitizer instrumentation is used. + +For an old source tree containing the unchecked conversion, use: + +```sh +Rscript --vanilla .github/development/test-polynomial-scheduling.R \ + /path/to/baseline --checked-baseline +``` + +This mode replaces only the original remaining-count declaration with a +checked conversion wrapper. It retains the extracted arithmetic and rejects +nonfinite or out-of-range values before casting. It permits negative fractions +that truncate to zero, as C++ does. The comparison is an instrumented arithmetic +diagnostic, not an execution of the original undefined conversion or a +public-API crash reproduction. Default mode refuses the known unchecked +declaration if the flag is omitted. Seven synthetic cases remain fixed-only; +these include arithmetic hazards beyond this conversion guard. + +The ordinary package regression in +[testQuadraticSieve.R](../../tests/testthat/testQuadraticSieve.R) separately +checks exact factors and input reconstruction for a fixed 162-bit semiprime +with one and two threads. Its parallel call reaches MPQS worker batches; +helper boundary coverage remains in the manual runner. Record measured +before/after results in [DEFERRED_ISSUES.md](DEFERRED_ISSUES.md). + ## GMP divisor allocation diagnostics After building an isolated installation, run from the repository root: diff --git a/NEWS.md b/NEWS.md index 485e424..064e83b 100644 --- a/NEWS.md +++ b/NEWS.md @@ -9,6 +9,7 @@ * Fixed constrained Pollard rho discarding unfinished cofactors when a recursive call exhausts its iteration budget. These cofactors are now retained for later factorization stages. * Fixed GMP allocation leaks during divisor generation by automatically releasing the divisor storage and temporary large integers used by `divisorsBig()`. * Fixed empty inputs returning an uninitialized integer. `primeFactorizeBig()`, `quadraticSieve()`, and `divisorsBig()` now return an unnamed empty vector of class `bigz` for empty inputs. +* Fixed invalid work estimates after parallel polynomial batches reach or exceed the relation target. When more relations are needed, invalid or empty batch estimates now trigger the existing serial fallback. ## Improvements diff --git a/inst/NEWS.Rd b/inst/NEWS.Rd index 7de89b5..3d2c1dc 100644 --- a/inst/NEWS.Rd +++ b/inst/NEWS.Rd @@ -28,6 +28,9 @@ \code{primeFactorizeBig()}, \code{quadraticSieve()}, and \code{divisorsBig()} now return an unnamed empty vector of class \code{bigz} for empty inputs. + \item Fixed invalid work estimates after parallel polynomial batches + reach or exceed the relation target. When more relations are needed, + invalid or empty batch estimates now trigger the existing serial fallback. } } \subsection{Improvements}{ diff --git a/src/Polynomial.cpp b/src/Polynomial.cpp index 4b030cb..f90388b 100644 --- a/src/Polynomial.cpp +++ b/src/Polynomial.cpp @@ -1,6 +1,9 @@ #include "cpp11/protect.hpp" #include "SolutionSearch.h" #include "Polynomial.h" +#include +#include +#include #include #include #include @@ -180,9 +183,22 @@ void SetThreadsPolys(std::size_t currLim, std::size_t SaPThresh, std::size_t &polysPerThread, std::size_t nPolys, typeTimeDiff totalTime) { + // No parallel batch: the caller retains its serial/solution-search logic. + nThreads = 0; + polysPerThread = 0; + + if (currLim >= SaPThresh || nPolys == 0 || maxThreads < 2) { + return; + } + const double percentComplete = (0.01 + 100.0 * currLim) / SaPThresh; const double percentRemaining = 100 - percentComplete; + // Very large, nearly equal counts can round to 100 percent completion. + if (percentRemaining <= 0) { + return; + } + // This was obtained experimentally. The idea is that if we have // only completed a small percentage, we really don't know how // quickly the growth can be. Thus, we penalize these more @@ -190,24 +206,84 @@ void SetThreadsPolys(std::size_t currLim, std::size_t SaPThresh, // is ~ 3.178 and when percentRemaining = 0, fudge ~= 1.386 const double fudge = std::log(percentRemaining * 0.2 + 4); - const std::size_t nPolysRemaining = percentRemaining * + const double estimatedPolys = percentRemaining * (static_cast(nPolys) / (fudge * percentComplete)); - nThreads = std::min(maxThreads, nPolysRemaining / MinPolysPerThrd); + // SIZE_MAX may round upward as a double, so keep this bound strict. + const double sizeLimit = static_cast( + std::numeric_limits::max() + ); - if (nThreads) { - const std::size_t maxPolys = nPolysRemaining / nThreads; - const auto timePerPoly = nThreads * totalTime / nPolys; - const auto maxTime = maxPolys * timePerPoly; + if (!std::isfinite(estimatedPolys) || estimatedPolys <= 0 || + estimatedPolys >= sizeLimit) { + return; + } - if (maxTime > (2 * fifteenSeconds)) { - polysPerThread = 2 * fifteenSeconds / timePerPoly; - } else if (maxTime > fifteenSeconds) { - polysPerThread = fifteenSeconds / timePerPoly; - } else { - polysPerThread = maxPolys; - } + const std::size_t nPolysRemaining = static_cast(estimatedPolys); + const std::size_t threads = std::min( + maxThreads, nPolysRemaining / MinPolysPerThrd + ); + + if (threads < 2) { + return; } + + const std::size_t maxPolys = nPolysRemaining / threads; + // Preserve the original clock-tick truncation and 15/30-second decisions. + // Multiplying by size_t can promote a signed clock rep to unsigned, so + // check the representation actually used by chrono's arithmetic. + using TimeRep = typename decltype(threads * totalTime)::rep; + const auto tickLimit = std::numeric_limits::max(); + + if (!std::isfinite(totalTime.count()) || totalTime.count() <= 0 || + static_cast(totalTime.count()) > tickLimit / threads) { + return; + } + + const auto timePerPoly = threads * totalTime / nPolys; + + // A zero integer average is valid truncation: the old policy uses the + // full batch and never divides by that zero duration. + if (!std::isfinite(timePerPoly.count()) || + (std::is_floating_point::value && timePerPoly.count() == 0) || + timePerPoly.count() > tickLimit / maxPolys) { + return; + } + + const auto maxTime = maxPolys * timePerPoly; + using CompareTime = typename std::common_type< + decltype(maxTime), decltype(fifteenSeconds) + >::type; + using ClockScale = std::ratio_divide< + typename typeTimeDiff::period, typename CompareTime::period + >; + using BudgetScale = std::ratio_divide< + typename decltype(fifteenSeconds)::period, typename CompareTime::period + >; + const auto compareLimit = std::numeric_limits::max(); + + // Comparisons and duration division convert both operands to their common + // tick period. Bound those conversions too (not just the products above). + if (!std::isfinite(maxTime.count()) || + maxTime.count() > compareLimit / ClockScale::num || + (2 * fifteenSeconds).count() > compareLimit / BudgetScale::num) { + return; + } + + std::size_t batchSize = maxPolys; + + if (maxTime > (2 * fifteenSeconds)) { + batchSize = 2 * fifteenSeconds / timePerPoly; + } else if (maxTime > fifteenSeconds) { + batchSize = fifteenSeconds / timePerPoly; + } + + if (batchSize == 0) { + return; + } + + nThreads = threads; + polysPerThread = batchSize; } void Polynomial::FactorParallel( diff --git a/tests/testthat/testQuadraticSieve.R b/tests/testthat/testQuadraticSieve.R index e8cf544..f93f62f 100644 --- a/tests/testthat/testQuadraticSieve.R +++ b/tests/testthat/testQuadraticSieve.R @@ -109,6 +109,20 @@ test_that("quadraticSieve generates correct numbers with multiple threads", { expect_equal(prod(quadraticSieve(prod(test6), nThreads = 2)), prod(test6)) }) +test_that("quadraticSieve returns exact factors in serial and parallel", { + ## This 162-bit semiprime reaches MPQS and exceeds its parallel cutoff. + input <- as.bigz("2923003274661805836407421649242809468366377451741") + expected <- as.bigz(c( + "1208925819614629174706189", "2417851639229258349412369" + )) + + for (threads in c(1L, 2L)) { + factors <- quadraticSieve(input, nThreads = threads) + expect_identical(factors, expected) + expect_identical(prod(factors), input) + } +}) + test_that("quadraticSieve produces appropriate error messages", { expect_error(quadraticSieve(0), "Cannot factorize 0") expect_error(quadraticSieve(1234567, nThreads = "9"),