← Back to Pull requests

Preflight functools.partial keyword index allocations #950

Open
Pybsama opened this pull request with 152 lines diff across 4 files
View on GitHub
Pybsama Pybsama commented on Sep 28, 2026 10:37 UTC
Author

Fixes #921.

functools.partial builds a keyword-name index once it has more than eight bound keywords. Previously, building that index copied every name without checking the configured memory budget. Nine large names under a 12 MiB limit could terminate the worker instead of returning a sandbox MemoryError.

Preflight the index's name copies and table allocation before building it, including spare buckets, rounding and control bytes, and check new-name/table growth while merging. If the preflight rejects a merge, release the arguments that have not been transferred yet. This keeps the existing indexed merge behavior when memory is available. Document the preflight in the resource-limit guide and limitations page.

Validation: the new subprocess regression fails on the original code and passes with the fix, including a 32 MiB successful control and a memory-model-checks worker build. All 67 pool integration tests and four Monty/CPython functools.partial data tests pass. Nightly formatting, Markdown formatting and targeted Clippy checks pass. The repository-wide make lint-rs is blocked on an unchanged stable_heap.rs warning from local Clippy 1.96; the targeted Clippy runs excluded that and other unchanged baseline warnings.

AI assistance disclosure: OpenAI Codex helped prepare the implementation, regression test and this description.

<!-- This is an auto-generated description by cubic. -->
---

Summary by cubic


Preflights functools.partial's keyword-name index allocations so an oversized index raises a sandbox MemoryError instead of terminating the worker at the hard memory limit.

  • Counts name-copy bytes and table space (spare buckets, power-of-two rounding and control bytes) before the first allocation, and checks the same growth when a merge adds a new name.

  • Releases incoming arguments not yet transferred when a preflight rejects a merge.

  • Adds a subprocess regression test that fails on the original code, passing under a 12 MiB budget and a 32 MiB control, and documents the preflight in both resource-limit docs.
  • <sup>Written for commit 08b074f14d6e3d26ea23c5ce130b3f7693ca0830. Summary will update on new commits.</sup>

    <a href="https://cubic.dev/pr/pydantic/monty/pull/950?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>

    <!-- End of auto-generated description by cubic. -->

    Diff: 152 lines (+135 / -17) across 4 files Reviewer: davidhewitt Review duration: 23375m
    All Vouch review confidence checks passed
    Residual risk 0.03 = Change Risk (0.37) × (1 − Review Confidence (0.92)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.37 · 152 lines diff across 4 files
    0.37
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 3 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    91%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.301
    Real PR Conversation Timeline
    6 items
    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on Sep 28, 2026 10:44 UTC
    Reviewer

    <!-- cubic:review-summary:start -->
    1 issue found across 4 files
    <!-- cubic:review-summary:end -->

    <details>
    <summary>Prompt for AI agents (unresolved issues)</summary>

    
    Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
    
    
    <file name="crates/monty/src/types/partial.rs">
    
    <violation number="1" location="crates/monty/src/types/partial.rs:235">
    P3: `merge_keywords` was rewritten from a `for` into this `while` loop, and its own doc comment states the keyword count is caller-controlled (`partial(f, **thousands)`) with no execution checkpoint inside. The checks this PR adds are memory-only (`check_allocation` never touches the time budgets), so a large merge can run long past `max_feed_duration`/`max_turn_duration` without any enforcement. The common path is bounded by the Python work that built the keyword list (which checkpointed), but a partial restored from a dump or built from host-supplied data has no such bound. Add an amortized `tracker.check_time_every(i)` guard (every 64th iteration) while this loop is being touched; the pool hard deadline is only a backstop when a `request_timeout` is actually configured.</violation>
    </file>
    

    </details>

    <sub>Reply with feedback, questions, or to request a fix.<br /><br />Fix all with cubic | Re-trigger cubic</sub>

    <!-- cubic:review-post:ai_pr_review_github_delivery_4e09f2ee40495aaecced624625ddef9c5582de675fc4ab2bb00c83e2546525a8:08b074f14d6e3d26ea23c5ce130b3f7693ca0830:badc18c8-9da5-5df3-ab2c-85a881b3cd48 -->

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Sep 28, 2026 10:44 UTC
    Code Review
    crates/monty/src/types/partial.rs:1
    @@ -220,13 +224,23 @@ const KEYWORD_INDEX_THRESHOLD: usize = 8;
     /// controlled (`partial(f, **thousands)`) and nothing here reaches an execution
     /// checkpoint. Past [`KEYWORD_INDEX_THRESHOLD`] it therefore builds a name
     /// index and keeps it current, which the pushes below rely on.
    -fn merge_keywords(bound: &mut Vec<(Value, Value)>, keywords: impl Iterator<Item = (Value, Value)>, vm: &mut VM<'_>) {
    +fn merge_keywords(
    +    bound: &mut Vec<(Value, Value)>,
    +    mut keywords: impl Iterator<Item = (Value, Value)>,
    +    vm: &mut VM<'_>,
    +) -> RunResult<()> {
         // Built lazily rather than up front because `bound` usually starts empty
         // and grows past the threshold during this very loop.
         let mut index: Option<AHashMap<String, usize>> = None;
    -    for (name, value) in keywords {
    +    while let Some((name, value)) = keywords.next() {

    <!-- cubic:v=b19213c1-8edc-4d57-833b-e5ced655da3b -->
    <!-- cubic:review-run=badc18c8-9da5-5df3-ab2c-85a881b3cd48 -->
    <!-- metadata:{"confidence":5} -->
    P3: merge_keywords was rewritten from a for into this while loop, and its own doc comment states the keyword count is caller-controlled (partial(f, **thousands)) with no execution checkpoint inside. The checks this PR adds are memory-only (check_allocation never touches the time budgets), so a large merge can run long past max_feed_duration/max_turn_duration without any enforcement. The common path is bounded by the Python work that built the keyword list (which checkpointed), but a partial restored from a dump or built from host-supplied data has no such bound. Add an amortized tracker.check_time_every(i) guard (every 64th iteration) while this loop is being touched; the pool hard deadline is only a backstop when a request_timeout is actually configured.

    <details>
    <summary>Prompt for AI agents</summary>

    Check if this issue is valid — if so, understand the root cause and fix it. At crates/monty/src/types/partial.rs, line 235:
    
    <comment>`merge_keywords` was rewritten from a `for` into this `while` loop, and its own doc comment states the keyword count is caller-controlled (`partial(f, **thousands)`) with no execution checkpoint inside. The checks this PR adds are memory-only (`check_allocation` never touches the time budgets), so a large merge can run long past `max_feed_duration`/`max_turn_duration` without any enforcement. The common path is bounded by the Python work that built the keyword list (which checkpointed), but a partial restored from a dump or built from host-supplied data has no such bound. Add an amortized `tracker.check_time_every(i)` guard (every 64th iteration) while this loop is being touched; the pool hard deadline is only a backstop when a `request_timeout` is actually configured.</comment>
    
    <file context>
    @@ -220,13 +224,23 @@ const KEYWORD_INDEX_THRESHOLD: usize = 8;
         // and grows past the threshold during this very loop.
         let mut index: Option<AHashMap<String, usize>> = None;
    -    for (name, value) in keywords {
    +    while let Some((name, value)) = keywords.next() {
             if index.is_none() && bound.len() > KEYWORD_INDEX_THRESHOLD {
    -            index = Some(keyword_index_map(bound, vm));
    </file context>
    

    </details>

    <a href="https://www.cubic.dev/action/fix/violation/b19213c1-8edc-4d57-833b-e5ced655da3b" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
    <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
    <source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
    <img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
    </picture>
    </a>

    codecov[bot] codecov[bot] commented on Sep 28, 2026 10:47 UTC
    Bot

    Codecov Report


    :x: Patch coverage is 17.18750% with 53 lines in your changes missing coverage. Please review.
    | Files with missing lines | Patch % | Lines |
    |---|---|---|
    | crates/monty/src/types/partial.rs | 17.18% | 50 Missing and 3 partials :warning: |

    :loudspeaker: Thoughts on this report? Let us know!

    codspeed[bot] codspeed[bot] commented on Sep 28, 2026 10:55 UTC
    Bot

    <!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->

    Merging this PR will not alter performance

    ✅ 45 untouched benchmarks
    ⏩ 16 skipped benchmarks[^skipped]

    ---

    <sub>Comparing <code>Pybsama:codex/partial-keyword-memory</code> (08b074f) with <code>main</code> (15753b3)</sub>

    <a href="https://app.codspeed.io/pydantic/monty/branches/Pybsama%3Acodex%2Fpartial-keyword-memory?utm_source=github&utm_medium=comment-v2&utm_content=button">
    <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
    <source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
    <img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
    </picture>
    </a>

    [^skipped]: 16 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

    davidhewitt davidhewitt requested changes on Oct 05, 2026 10:49 UTC
    Changes Requested Reviewer

    Thanks, I think this is the wrong fix.

    Rather than increasing complexity in partial.rs we should seek to throw away code there. I think KwargsValues::Dict already contains a mapping form and we should aim to merge keywords into that form instead.

    Reviewers
    Assignees
    Pybsama Pybsama
    Labels
    risk: low confidence: 91.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 37.5% (MEDIUM) · Higher = larger blast radius
    37.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 91.8% · Lower = rushed or shallow review
    91.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 3.1% · Safe to merge
    3.1%
    Repository