diff --git a/.github/development/DEFERRED_ISSUES.md b/.github/development/DEFERRED_ISSUES.md index 496bd46..48be7fe 100644 --- a/.github/development/DEFERRED_ISSUES.md +++ b/.github/development/DEFERRED_ISSUES.md @@ -347,7 +347,7 @@ Next step: Include the fix in the next release and record its version here. ## Parallel polynomial scheduling estimates work after completion -Status: Implemented and tested locally; not yet merged or released +Status: Safety fix merged in [PR #20](https://github.com/jwood000/RcppBigIntAlgos/pull/20) (`9cda1b4`); timing simplification implemented and tested locally; not yet released Priority: Medium Evidence: Source review, guarded native baseline comparison, and serial/parallel public-API checks @@ -359,7 +359,7 @@ 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 merged helper 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 @@ -385,7 +385,7 @@ 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 +At merge, the development-only [native runner](test-polynomial-scheduling.R) passed 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, @@ -426,7 +426,30 @@ 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. +The follow-up timing simplification removes the promoted-representation and +common-period guards above. It converts elapsed time to floating-point seconds, +checks finite positive timing estimates, and compares by division instead of +multiplying a potentially large batch count. The time-limited count is capped +before conversion to `size_t`; fewer than one polynomial still triggers serial +fallback. No epsilon or minimum-one override is introduced. + +The progress estimate, worker-selection rule, multiplication/division order, +and 15/30-second budget policy remain the same. Exact integer-clock truncation +is intentionally no longer preserved: boundary rounding can change a batch +size or select serial fallback. The historical equality checks above document +the merged version, not a compatibility requirement for this simplification. +Current diagnostics test safety and the seconds-based policy instead. + +The updated development-only runner passes all 52 cases. It covers floating +overflow and underflow, coarse/fine clocks, fractional ticks, large bounded +counts, and clear values on both sides of the one-polynomial limit. A fresh +source-archive `R CMD check --no-manual` finishes with `Status: OK`; all 500 +package expectations pass without failures, warnings, or skips. Independent +source review found no actionable defects. No sanitizers, new dependencies, +or CI changes were used. These checks do not establish a performance change. + +Next step: Review the timing simplification separately from the +relation-storage refactor, 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 index 4fe7854..7b73761 100644 --- a/.github/development/test-polynomial-scheduling.R +++ b/.github/development/test-polynomial-scheduling.R @@ -80,7 +80,9 @@ cpp11::writable::list run_polynomial_schedule( try { if (floating) { const double seconds = elapsed == "denorm_min" ? - std::numeric_limits::denorm_min() : std::stod(elapsed); + std::numeric_limits::denorm_min() : + elapsed == "double_max" ? std::numeric_limits::max() : + std::stod(elapsed); SetThreadsPolys(currLim, threshold, nThreads, maximum, polysPerThread, nPolys, std::chrono::duration(seconds)); } else { @@ -121,7 +123,7 @@ cpp11::writable::list run_polynomial_schedule( code <- paste(c( '#include ', '#include ', '#include ', '#include ', '#include ', '#include ', - '#include ', '#include ', '#include ', + '#include ', '#include ', '#include ', sprintf('#include %s', encodeString(stats, quote = '"')), minimum, support, helper, wrapper @@ -166,52 +168,58 @@ cpp11::writable::list run_polynomial_schedule( 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("finite seconds overflow when scaled by workers", elapsed = "double_max", + floating = TRUE, baseline = FALSE), 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", + case("maximum integral duration safely converted to seconds", elapsed = "max", baseline = FALSE), + case("large worker-scaled time safely exceeds the budget", elapsed = "2305843009213693952", baseline = FALSE), - case("full-batch duration overflows its chrono representation", + case("large estimated batch with excessive time per polynomial", current = 0L, processed = 40L, elapsed = "10000000000000", baseline = FALSE), - case("worker-scaled duration fits the promoted unsigned representation", + case("large integral duration retains a one-polynomial budget", processed = 1000000000L, elapsed = "2000000000000000000", threads = "8", polys = "1"), - case("coarse clock preserves duration comparison and division", + case("coarse clock is converted to floating seconds", elapsed = "1000", period = "three-halves", threads = "8", polys = "2"), - case("clock conversion overflows the common comparison period", + case("very large coarse-clock duration safely exceeds the budget", workers = 2L, elapsed = "8000000000000000000", period = "three-halves", baseline = FALSE), - case("time budget conversion overflows the common comparison period", - period = "attoseconds", baseline = FALSE), + case("fine clock retains a positive average in seconds", + period = "attoseconds", threads = "8", polys = "127", 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", + case("one polynomial fits below the time budget", + elapsed = "3749000000000", threads = "8", polys = "1"), + case("one polynomial exceeds the time budget", + elapsed = "3751000000000"), + case("uneven division below a one-polynomial budget", + current = 1L, processed = 57L, workers = 25L, + elapsed = "68000000000", threads = "25", polys = "1"), + case("uneven division above a one-polynomial budget", current = 1L, processed = 57L, workers = 25L, - elapsed = "68400000000", threads = "25", polys = "1"), + elapsed = "69000000000"), case("estimate outside size_t range", processed = "max"), case("large safe estimate", current = 1999L, processed = "max", threads = "8", polys = NA_character_, baseline = FALSE), + case("large safe estimate with tiny positive seconds stays bounded", + current = 1999L, processed = "max", elapsed = "1e-200", floating = TRUE, + 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("fractional ticks above the 15-second boundary", current = 1500L, + elapsed = "100000000100", threads = "3", polys = "49"), 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("fractional ticks above the 30-second boundary", current = 1500L, + elapsed = "200000000100", 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", diff --git a/.github/development/testing.md b/.github/development/testing.md index 9e4cae6..7ac4ccd 100644 --- a/.github/development/testing.md +++ b/.github/development/testing.md @@ -187,13 +187,13 @@ 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 +The 52 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. +the 15/30-second batch caps. Timing cases check the seconds-based policy, +including fractional ticks and values on both sides of the one-polynomial +limit. They do not require historical integer-clock truncation. Additional +cases cover nonfinite estimates, floating overflow/underflow, large bounded +counts, and coarse/fine clocks converted to seconds. 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 @@ -212,8 +212,9 @@ 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. +declaration if the flag is omitted. Synthetic cases involving arithmetic +hazards beyond this conversion guard remain fixed-only. Historical sources +may also fail timing-policy expectations because they truncate clock ticks. The ordinary package regression in [testQuadraticSieve.R](../../tests/testthat/testQuadraticSieve.R) separately diff --git a/NEWS.md b/NEWS.md index 064e83b..253abe5 100644 --- a/NEWS.md +++ b/NEWS.md @@ -13,6 +13,7 @@ ## Improvements +* Simplified parallel polynomial batch timing to use floating-point seconds while retaining the existing work estimates, 15/30-second budgets, and serial fallback. Batch sizes can differ near timing boundaries. * Added a load-time check that the compiled library version matches the R package version, with reinstall guidance for mismatched installations. * Added a package citation, available through `citation("RcppBigIntAlgos")`. diff --git a/inst/NEWS.Rd b/inst/NEWS.Rd index 3d2c1dc..99916f9 100644 --- a/inst/NEWS.Rd +++ b/inst/NEWS.Rd @@ -35,6 +35,9 @@ } \subsection{Improvements}{ \itemize{ + \item Simplified parallel polynomial batch timing to use floating-point + seconds while retaining the existing work estimates, 15/30-second + budgets, and serial fallback. Batch sizes can differ near timing boundaries. \item Added a load-time check that the compiled library version matches the R package version, with reinstall guidance for mismatched installations. diff --git a/src/Polynomial.cpp b/src/Polynomial.cpp index f90388b..e776839 100644 --- a/src/Polynomial.cpp +++ b/src/Polynomial.cpp @@ -3,7 +3,6 @@ #include "Polynomial.h" #include #include -#include #include #include #include @@ -229,57 +228,35 @@ void SetThreadsPolys(std::size_t currLim, std::size_t SaPThresh, } 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) { + // Timing is an estimate: use seconds rather than integral clock products. + const double seconds = std::chrono::duration(totalTime).count(); + + if (!std::isfinite(seconds) || seconds <= 0) { return; } - const auto timePerPoly = threads * totalTime / nPolys; + const double timePerPoly = threads * seconds / 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) { + if (!std::isfinite(timePerPoly) || timePerPoly <= 0) { 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; - } + const double limit = std::chrono::duration(fifteenSeconds).count(); std::size_t batchSize = maxPolys; - if (maxTime > (2 * fifteenSeconds)) { - batchSize = 2 * fifteenSeconds / timePerPoly; - } else if (maxTime > fifteenSeconds) { - batchSize = fifteenSeconds / timePerPoly; - } + // Comparing by division avoids multiplying a potentially large batch. + if (timePerPoly > limit / maxPolys) { + const double budget = timePerPoly > 2 * limit / maxPolys ? 2 * limit : limit; + const double limited = budget / timePerPoly; - if (batchSize == 0) { - return; + if (!std::isfinite(limited) || limited < 1) { + return; + } + + // Cap before converting; maxPolys is below half the size_t range. + batchSize = limited >= static_cast(maxPolys) ? + maxPolys : static_cast(limited); } nThreads = threads;