← Back to Pull requests

Check str case methods and re.escape against max_memory #1389

Closed
unknown closed this pull request without merging on Nov 23, 2026 14:01 UTC
View on GitHub
unknown unknown commented on Nov 19, 2026 03:34 UTC
Author

Summary

With max_memory set, the str case methods and re.escape can kill the worker instead of raising MemoryError:

monty --max-memory 12MB -c "s = 'x' 9_000_000; y = s.upper()"
monty worker: allocation of 9000000 bytes exceeds the memory limit (exit 65)

monty --max-memory 8MB -c "import re; y = re.escape(' ' 4_500_000)"
monty worker: allocation of 9000000 bytes exceeds the memory limit (exit 65)

Both build their result in a plain String that the tracker never sees, so a large enough input crosses the hard ceiling before the next checkpoint. Lowercasing or escaping a document that is a good fraction of the budget is ordinary code, so this seemed worth the same graceful path the split and findall preflights have.

Changes:

  • re.escape: pre-check the existing 2 len reservation with check_estimated_size. The loop is unchanged.

  • ASCII lower/upper/casefold: pre-check s.len(), which is exact.

  • Everything else (non-ASCII input, and capitalize/title/swapcase) goes through a new map_case helper in unicode_type.rs. A mapping can be longer than its input ('ɐ'.upper() is 3 bytes from 2, 'ΐ'.upper() is 6 from 2), so a check sized to the input is not enough. For inputs over LARGE_RESULT_THRESHOLD / 12 bytes, map_case checks the initial buffer and every later growth with check_allocation, and maps in chunks that cannot reallocate behind the check. Smaller inputs take the old path unchanged. I didn't use StringBuilder here because its 2x growth would refuse results that fit, and the per-char Result cost about 20% on short non-ASCII strings.

  • Updated the pre-checked lists in limitations/resource_limits.md, docs/resource-limits.md and CLAUDE.md, and dropped s.to_lowercase() from CLAUDE.md's "already bounded" examples.
  • bytes.lower() and friends are left alone because #1208 already adds check_allocation to them.

    Tests

  • Added cases to large_allocations_are_rejected_before_the_hard_limit: ASCII lower and title, 'é' (non-ASCII, same length), 'ΐ'.upper() (fails in the growth check, not the initial one) and re.escape. On main the test fails with monty worker: allocation of 16777216 bytes exceeds the memory limit / unexpected EOF from worker. With this change it passes.

  • Added asserts to test_cases/str__methods.py with inputs over the threshold, so the chunked path is checked against CPython (expansion, final sigma, title, swapcase, capitalize, casefold).

  • cargo test -p monty-runtime --test subprocess, cargo test -p monty and make test-cases all pass, along with make format-rs lint-rs lint-py lint-md.

  • A sweep over 5 chars (ɐ ΐ İ é ß), 4 methods and 15 sizes up to 15 MiB at a 24 MiB limit: main killed the worker in 8 of 300 runs, this branch in 0. Those 8 now raise MemoryError, and every other run gives the same result on both.

  • Timing on release builds, best of 9 runs: 20-char and 1 MB strings, ASCII and non-ASCII, are all within noise of main. A 1 MB string that expands on upper() is about 30% faster, because it reallocates a few times instead of doubling. re.escape is unchanged.
  • I have read the contribution guide.

  • I understand and can explain the proposed changes, including any generated with AI assistance.
  • <!-- This is an auto-generated description by cubic. -->
    ---

    Summary by cubic


    Fixes str case methods and re.escape killing the worker with max_memory set instead of raising MemoryError. Both previously built their result in a plain String that the memory tracker never saw, so a large enough input crossed the hard ceiling before the next checkpoint.

  • re.escape pre-checks its existing 2 len reservation with check_estimated_size; the loop is unchanged.

  • ASCII lower/upper/casefold pre-check s.len(), which is exact.

  • Non-ASCII mappings go through a new map_case helper that checks the initial buffer and every later growth for inputs over LARGE_RESULT_THRESHOLD / 12 bytes; smaller inputs take the old path.

  • bytes.lower() and friends are left alone; #1208 already adds check_allocation to them.
  • <sup>Written for commit 210682f1396a23dd6fc9284d261bdd0e21cdd2f4. Summary will update on new commits.</sup>

    <a href="https://cubic.dev/pr/pydantic/monty/pull/1389?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="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>

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

    Diff: 597 lines (+447 / -150) across 7 files Reviewer: davidhewitt Review duration: 6386m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.50) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.50 · 597 lines diff across 7 files
    0.50
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    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.383
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #1389"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.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: 50% (MEDIUM) · Higher = larger blast radius
    50%
    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: 56.8% · Lower = rushed or shallow review
    56.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: 21.6% · Safe to merge
    21.6%
    Repository