Skip to content

Fixed #34746 -- Used reprlib to limit variable size in debug reports. - #20578

Open
abdullahmujahidali wants to merge 1 commit into
django:mainfrom
abdullahmujahidali:ticket_34746
Open

abdullahmujahidali wants to merge 1 commit into
django:mainfrom
abdullahmujahidali:ticket_34746

Conversation

@abdullahmujahidali

@abdullahmujahidali abdullahmujahidali commented Jan 24, 2026 •

Copy link
Copy Markdown

This prevents high CPU and memory consumption when a 5XX error is raised with large local variables. The reprlib module limits output size during generation rather than after, avoiding the need to fully expand large objects before truncating.

Trac ticket number

ticket-34746

Branch description

Replaced pprint with reprlib.Repr() to limit variable representation size during generation, preventing high memory/CPU usage when displaying large variables in the technical 500 debug page.

AI Assistance Disclosure (REQUIRED)

  • No AI tools were used in preparing this PR.
  • If AI tools were used, I have disclosed which ones, and fully reviewed and verified their output.

Checklist

  • This PR follows the contribution guidelines.
  • This PR does not disclose a security vulnerability (see vulnerability reporting).
  • This PR targets the main branch.
  • The commit message is written in past tense, mentions the ticket number, and ends with a period.
  • I have checked the "Has patch" ticket flag in the Trac system.
  • I have added or updated relevant tests.
  • I have added or updated relevant docs, including release notes if applicable.
  • I have attached screenshots in both light and dark modes for any UI changes.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hello! Thank you for your contribution 💪

As it's your first contribution be sure to check out the patch review checklist.

If you're fixing a ticket from Trac make sure to set the "Has patch" flag and include a link to this PR in the ticket!

If you have any design or process questions then you can ask in the Django forum.

Welcome aboard ⛵️!

@abdullahmujahidali abdullahmujahidali changed the title Fixed #34746 used reprlib to limit var size in debug error page Fixed -- #34746 used reprlib to limit size in debug error page Jan 25, 2026
@abdullahmujahidali abdullahmujahidali changed the title Fixed -- #34746 used reprlib to limit size in debug error page Fixed #34746 -- used reprlib to limit size in debug error page Jan 25, 2026
@github-actions

Copy link
Copy Markdown

📊 Coverage Report for Changed Files

-------------
Diff Coverage
Diff: origin/main...HEAD, staged and unstaged changes
-------------
django/views/debug.py (87.5%): Missing lines 375-376
-------------
Total:   16 lines
Missing: 2 lines
Coverage: 87%
-------------


Note: Missing lines are warnings only. Some lines may not be covered by SQLite tests as they are database-specific.

For more information about code coverage on pull requests, see the contributing documentation.

@abdullahmujahidali abdullahmujahidali changed the title Fixed #34746 -- used reprlib to limit size in debug error page Fixed #34746 -- Used reprlib to limit variable size in debug reports. Oct 11, 2026
Comment thread django/views/debug.py Outdated
frames = self.get_traceback_frames()
# Use reprlib to limit output size during generation, avoiding
# high memory consumption for large variables.
r = reprlib.Repr()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From Python 3.12+, the attributes can be passed directly to the constructor, rather than being set as attributes manually.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done thanks

Comment thread django/views/debug.py Outdated
frames = self.get_traceback_frames()
# Use reprlib to limit output size during generation, avoiding
# high memory consumption for large variables.
r = reprlib.Repr()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thought: It looks like the Repr is safe for reuse. Should one be created at the module level to avoid needing to recreate the instance? reprlib creates one at the module level, so it shouldn't cause many issues.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved it to a module-level DEBUG_REPR next to DEBUG_ENGINE

@jacobtylerwalls

Copy link
Copy Markdown
Member

Thanks @abdullahmujahidali, could you resolve the conflicts?

@abdullahmujahidali

Copy link
Copy Markdown
Author

Thanks @abdullahmujahidali, could you resolve the conflicts?

Rebased and resolved the conflicts. reprlib already limits strings to 200 chars I dropped the trim_value() call in the debug view

@jacobtylerwalls jacobtylerwalls added the coverage Generate a comment with a coverage diff label Nov 5, 2026

@jacobtylerwalls jacobtylerwalls left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for this, I have initial comments.

Comment thread django/views/debug.py Outdated
# Limit the size of variable representations during generation, avoiding high
# memory consumption for large variables.
DEBUG_REPR = reprlib.Repr(
maxlevel=3,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These values seem quite low.

Loading a dictionary from Django's own test suite (hasnulls.geojson), even adding a single additional level makes a huge difference in understanding the actual content:

>>> DEBUG_REPR.repr(dct)
"{'crs': {'properties': {'name': 'urn:ogc:def:crs:OGC:1.3:CRS84'}, 'type': 'name'}, 'features': [{'geometry': {...}, 'properties': {...}, 'type': 'Feature'}, {'geometry': {...}, 'properties': {...}, 'type': 'Feature'}, {'geometry': {...}, 'properties': {...}, 'type': 'Feature'}], 'name': 'has_nulls', 'type': 'FeatureCollection'}"
>>> DEBUG_REPR.maxlevel=4
>>> DEBUG_REPR.repr(dct)
"{'crs': {'properties': {'name': 'urn:ogc:def:crs:OGC:1.3:CRS84'}, 'type': 'name'}, 'features': [{'geometry': {'coordinates': [...], 'type': 'Polygon'}, 'properties': {'boolean': True, 'datetime': '1994-08-14T11:32:14.123+0000', 'integer': 5, 'name': 'Philadelphia', 'num': 1.001, 'time': '11:32:14.123', 'uuid': '1378c26f-cbe6-44b0-929f-eb330d4991f5'}, 'type': 'Feature'}, {'geometry': {'coordinates': [...], 'type': 'Polygon'}, 'properties': {'integer': None, 'num': None, 'uuid': 'fa2ba67c-a135-4338-b924-a9622b5d869f'}, 'type': 'Feature'}, {'geometry': {'coordinates': [...], 'type': 'Polygon'}, 'properties': {'boolean': False, 'datetime': '2018-11-29T03:02:52+0000', 'integer': 8, 'name': 'north', 'num': 0.0, 'time': '03:02:52', 'uuid': '4494c1f3-55ab-4256-b365-12115cb388d5'}, 'type': 'Feature'}], 'name': 'has_nulls', 'type': 'FeatureCollection'}"

I wonder if we can loosen some of these limits, and then still use the trim_value() helper to limit to a total length of 4096 like before.

In other words, I don't want to get follow-up issues on this about how we degraded the usefulness of the debug view.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Raised the limits a bit and added trim_value() back, so your geojson example shows in full now. Didn't go past 4 levels since it gets slow on deeply nested data.

Comment thread django/views/debug.py Outdated
Comment on lines +372 to +374
except Exception as e:
v = "Error in formatting: %s: %s" % (e.__class__.__name__, e)
frame_vars.append((k, v))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having to handle failing repr() is, I think, another reason to keep a total limit of 4096 length, because this passes through in its entirety.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep errors go through trim_value() now too

Comment thread tests/view_tests/tests/test_debug.py Outdated
self.assertNotIn("A" * 200, html)

def test_large_collection_values_handling(self):
"Large collections should not be fully rendered."

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use triple-quotes.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

Comment thread tests/view_tests/tests/test_debug.py Outdated
except Exception:
exc_type, exc_value, tb = sys.exc_info()
reporter = ExceptionReporter(None, exc_type, exc_value, tb)
with mock.patch("reprlib.Repr.repr", side_effect=MemoryError("OOM")):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't seem realistic. reprlib.repr() already has a bare except. Do we need this test and our own bare except, above?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right newer Pythons handle this, but on 3.12 reprlib still raises for very large ints, so I kept the except and tested that case instead of the mock.

Happy to drop it if you'd rather

Comment thread django/views/debug.py
maxdeque=10,
maxstring=200,
maxother=200,
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The existing helper used a placeholder similar to <trimmed>, should we use that instead of the default .?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done using fillvalue=""

Rendering every local variable with pprint built the full string before
trimming it to 4096 characters, so a frame holding a large object made
the error report slow and very memory hungry. reprlib stops early, so
the cost no longer grows with the size of the data.
@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown

Uncovered lines in changed files

-------------
django/views/debug.py (71.4%): Missing lines 374-375
-------------
Total:   7 lines
Missing: 2 lines
Coverage: 71%
-------------

Note: Missing lines are warnings only. Some database-specific lines may not be measured. More information

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

coverage Generate a comment with a coverage diff

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants