-
Notifications
You must be signed in to change notification settings - Fork 44
Add .iterator() to unbounded querysets#7940 #8019
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
acwhite211
wants to merge
3
commits into
main
Choose a base branch
from
issue-7864
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from typing import Any | ||
|
|
||
|
|
||
| def _field_to_cache_entry(field) -> dict[str, Any]: | ||
| return { | ||
| 'id': field.id, | ||
| 'exported_field_name': field.exportedfieldname, | ||
| 'extension_item': field.extensionitem, | ||
| 'remarks': field.remarks, | ||
| 'row_type': field.rowtype, | ||
| 'export_schema_item_id': field.exportschemaitem_id, | ||
| 'query_field_id': field.queryfield_id, | ||
| } | ||
|
|
||
|
|
||
| def _build_single_cache(extension, fields=None) -> dict[str, Any]: | ||
| if fields is None: | ||
| fields = extension.mappings | ||
|
|
||
| return { | ||
| 'id': extension.id, | ||
| 'mapping_name': extension.mappingname, | ||
| 'description': extension.description, | ||
| 'collection_member_id': extension.collectionmemberid, | ||
| 'timestamp_exported': extension.timestampexported, | ||
| 'fields': [ | ||
| _field_to_cache_entry(field) | ||
| for field in fields.all().iterator(chunk_size=2000) | ||
| ], | ||
| } | ||
|
|
||
|
|
||
| def build_cache_tables(extensions) -> list[dict[str, Any]]: | ||
| return [ | ||
| _build_single_cache(extension) | ||
| for extension in extensions.all().iterator(chunk_size=2000) | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| """Tests for queryset .iterator() usage in high-impact paths. | ||
|
|
||
| Verifies that key callsites that iterate over potentially large querysets | ||
| use .iterator(chunk_size=2000) to avoid caching all results in memory. | ||
| """ | ||
| import inspect | ||
| import textwrap | ||
| from django.test import TestCase | ||
|
|
||
|
|
||
| def _get_source(func): | ||
| """Return dedented source code for a function.""" | ||
| return textwrap.dedent(inspect.getsource(func)) | ||
|
|
||
|
|
||
| class TestIteratorUsageInSource(TestCase): | ||
| """Verify that high-impact callsites use .iterator() in their source code. | ||
|
|
||
| These are source-level checks — they inspect the actual Python source of | ||
| functions that iterate over potentially large querysets, and verify that | ||
| .iterator(chunk_size=2000) is present. | ||
| """ | ||
|
|
||
| def test_serializers_to_many_uses_iterator(self): | ||
| """to_many_to_data should use .iterator() when serializing dependent collections.""" | ||
| from specifyweb.specify.api.serializers import to_many_to_data | ||
| source = _get_source(to_many_to_data) | ||
| self.assertIn( | ||
| '.iterator(chunk_size=2000)', | ||
| source, | ||
| "to_many_to_data should use .iterator(chunk_size=2000) on objs.all()" | ||
| ) | ||
|
|
||
| def test_calculated_fields_deaccession_uses_iterator(self): | ||
| """calculate_totals_deaccession should use .iterator() on the filter queryset.""" | ||
| from specifyweb.specify.api.calculated_fields import calculate_totals_deaccession | ||
| source = _get_source(calculate_totals_deaccession) | ||
| self.assertIn( | ||
| '.iterator(chunk_size=2000)', | ||
| source, | ||
| "calculate_totals_deaccession should use .iterator(chunk_size=2000)" | ||
| ) | ||
|
|
||
| def test_print_tree_taxon_uses_iterator(self): | ||
| """print_tree management command should use .iterator() on Taxon.objects.all().""" | ||
| from specifyweb.specify.management.commands.print_tree import Command | ||
| source = _get_source(Command.handle) | ||
| self.assertIn( | ||
| '.iterator(chunk_size=2000)', | ||
| source, | ||
| "print_tree should use .iterator(chunk_size=2000) on Taxon.objects.all()" | ||
| ) | ||
|
|
||
| def test_export_extract_query_uses_iterator(self): | ||
| """extract_query should use .iterator() on query.fields.all().""" | ||
| from specifyweb.backend.export.extract_query import extract_query | ||
| source = _get_source(extract_query) | ||
| self.assertIn( | ||
| '.iterator(chunk_size=2000)', | ||
| source, | ||
| "extract_query should use .iterator(chunk_size=2000) on query.fields.all()" | ||
| ) | ||
|
|
||
| def test_export_cache_build_uses_iterator(self): | ||
| """build_cache_tables should use .iterator() on extensions.all().""" | ||
| from specifyweb.backend.export.cache import build_cache_tables | ||
| source = _get_source(build_cache_tables) | ||
| self.assertIn( | ||
| '.iterator(chunk_size=2000)', | ||
| source, | ||
| "build_cache_tables should use .iterator(chunk_size=2000) on extensions.all()" | ||
| ) | ||
|
|
||
| def test_export_cache_fields_uses_iterator(self): | ||
| """_build_single_cache should use .iterator() on fields.all().""" | ||
| from specifyweb.backend.export.cache import _build_single_cache | ||
| source = _get_source(_build_single_cache) | ||
| self.assertIn( | ||
| '.iterator(chunk_size=2000)', | ||
| source, | ||
| "_build_single_cache should use .iterator(chunk_size=2000) on fields.all()" | ||
| ) | ||
|
|
||
| def test_cog_preps_child_cogs_uses_iterator(self): | ||
| """get_cog_consolidated_preps should use .iterator() on child COG queries.""" | ||
| from specifyweb.backend.interactions.cog_preps import get_cog_consolidated_preps | ||
| source = _get_source(get_cog_consolidated_preps) | ||
| self.assertIn( | ||
| '.iterator(chunk_size=2000)', | ||
| source, | ||
| "get_cog_consolidated_preps should use .iterator(chunk_size=2000)" | ||
| ) | ||
|
|
||
| def test_permissions_serialize_role_uses_iterator(self): | ||
| """serialize_role should use .iterator() on role.policies.all().""" | ||
| from specifyweb.backend.permissions.views import serialize_role | ||
| source = _get_source(serialize_role) | ||
| self.assertIn( | ||
| '.iterator(chunk_size=2000)', | ||
| source, | ||
| "serialize_role should use .iterator(chunk_size=2000) on role.policies.all()" | ||
| ) | ||
|
|
||
| def test_tree_views_ranks_uses_iterator(self): | ||
| """get_all_tree_information should use .iterator() on treedefitems.""" | ||
| from specifyweb.backend.trees.views import get_all_tree_information | ||
| source = _get_source(get_all_tree_information) | ||
| self.assertIn( | ||
| '.iterator(chunk_size=2000)', | ||
| source, | ||
| "get_all_tree_information should use .iterator(chunk_size=2000) on ranks" | ||
| ) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Source inspection tests are brittle and will break with refactoring.
All nine test methods use string matching on source code to verify
.iterator(chunk_size=2000)usage. This approach has significant maintenance risks:.iterator()calls into a helper function, decorator, or mixin, these tests fail even though the behavior remains correct..iterator(chunk_size=2000)appears in comments, string literals, or unrelated context.Consider behavior-based alternatives that verify actual functionality:
QuerySet.iterator()and assert it's called withchunk_size=2000on the target querysets.assertNumQueriesor inspectconnection.queriesto verify batched query behavior.unittest.mock.patchwithwraps=Trueto spy on iterator calls without breaking behavior.If source inspection is retained as a temporary migration guard, document the brittleness and plan to migrate to behavior-based tests once the
.iterator()adoption is stable.🤖 Prompt for AI Agents