-
Notifications
You must be signed in to change notification settings - Fork 52.3k
fix: guard json.loads() and use atomic writes for persistent state #29019
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
annguyenNous
wants to merge
1
commit into
NousResearch:main
Choose a base branch
from
annguyenNous:fix/guard-json-loads-and-atomic-writes
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
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
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
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 |
|---|---|---|
|
|
@@ -346,62 +346,65 @@ def _resize_image_for_vision(image_path: Path, mime_type: Optional[str] = None, | |
| if data_url is None: | ||
| data_url = _image_to_base64_data_url(image_path, mime_type=mime_type) | ||
| return data_url # fall through to size-check in caller | ||
| # Convert RGBA to RGB for JPEG output | ||
| if pil_format == "JPEG" and img.mode in {"RGBA", "P"}: | ||
| img = img.convert("RGB") | ||
|
|
||
| # Strategy: halve dimensions until base64 fits, up to 4 rounds. | ||
| # For JPEG, also try reducing quality at each size step. | ||
| # For PNG, quality is irrelevant — only dimension reduction helps. | ||
| quality_steps = (85, 70, 50) if pil_format == "JPEG" else (None,) | ||
| prev_dims = (img.width, img.height) | ||
| candidate = None # will be set on first loop iteration | ||
|
|
||
| for attempt in range(5): | ||
| if attempt > 0: | ||
| # Proportional scaling: halve the longer side and scale the | ||
| # shorter side to preserve aspect ratio (min dimension 64). | ||
| scale = 0.5 | ||
| new_w = max(int(img.width * scale), 64) | ||
| new_h = max(int(img.height * scale), 64) | ||
| # Re-derive the scale from whichever dimension hit the floor | ||
| # so both axes shrink by the same factor. | ||
| if new_w == 64 and img.width > 0: | ||
| effective_scale = 64 / img.width | ||
| new_h = max(int(img.height * effective_scale), 64) | ||
| elif new_h == 64 and img.height > 0: | ||
| effective_scale = 64 / img.height | ||
| new_w = max(int(img.width * effective_scale), 64) | ||
| # Stop if dimensions can't shrink further | ||
| if (new_w, new_h) == prev_dims: | ||
| break | ||
| img = img.resize((new_w, new_h), Image.LANCZOS) | ||
| prev_dims = (new_w, new_h) | ||
| logger.info("Resized to %dx%d (attempt %d)", new_w, new_h, attempt) | ||
|
|
||
| for q in quality_steps: | ||
| buf = _io.BytesIO() | ||
| save_kwargs = {"format": pil_format} | ||
| if q is not None: | ||
| save_kwargs["quality"] = q | ||
| img.save(buf, **save_kwargs) | ||
| encoded = base64.b64encode(buf.getvalue()).decode("ascii") | ||
| candidate = f"data:{out_mime};base64,{encoded}" | ||
| if len(candidate) <= max_base64_bytes: | ||
| logger.info("Auto-resized image fits: %.1f MB (quality=%s, %dx%d)", | ||
| len(candidate) / (1024 * 1024), q, | ||
| img.width, img.height) | ||
| return candidate | ||
|
|
||
| # If we still can't get it small enough, return the best attempt | ||
| # and let the caller decide | ||
| if candidate is not None: | ||
| logger.warning("Auto-resize could not fit image under %.1f MB (best: %.1f MB)", | ||
| max_base64_bytes / (1024 * 1024), len(candidate) / (1024 * 1024)) | ||
| return candidate | ||
|
|
||
| # Shouldn't reach here, but fall back to full encode | ||
| return data_url or _image_to_base64_data_url(image_path, mime_type=mime_type) | ||
| try: | ||
| # Convert RGBA to RGB for JPEG output | ||
| if pil_format == "JPEG" and img.mode in {"RGBA", "P"}: | ||
| img = img.convert("RGB") | ||
|
|
||
| # Strategy: halve dimensions until base64 fits, up to 4 rounds. | ||
| # For JPEG, also try reducing quality at each size step. | ||
| # For PNG, quality is irrelevant — only dimension reduction helps. | ||
| quality_steps = (85, 70, 50) if pil_format == "JPEG" else (None,) | ||
| prev_dims = (img.width, img.height) | ||
| candidate = None # will be set on first loop iteration | ||
|
|
||
| for attempt in range(5): | ||
| if attempt > 0: | ||
| # Proportional scaling: halve the longer side and scale the | ||
| # shorter side to preserve aspect ratio (min dimension 64). | ||
| scale = 0.5 | ||
| new_w = max(int(img.width * scale), 64) | ||
| new_h = max(int(img.height * scale), 64) | ||
| # Re-derive the scale from whichever dimension hit the floor | ||
| # so both axes shrink by the same factor. | ||
| if new_w == 64 and img.width > 0: | ||
| effective_scale = 64 / img.width | ||
| new_h = max(int(img.height * effective_scale), 64) | ||
| elif new_h == 64 and img.height > 0: | ||
| effective_scale = 64 / img.height | ||
| new_w = max(int(img.width * effective_scale), 64) | ||
| # Stop if dimensions can't shrink further | ||
| if (new_w, new_h) == prev_dims: | ||
| break | ||
| img = img.resize((new_w, new_h), Image.LANCZOS) | ||
| prev_dims = (new_w, new_h) | ||
| logger.info("Resized to %dx%d (attempt %d)", new_w, new_h, attempt) | ||
|
|
||
| for q in quality_steps: | ||
| buf = _io.BytesIO() | ||
| save_kwargs = {"format": pil_format} | ||
| if q is not None: | ||
| save_kwargs["quality"] = q | ||
| img.save(buf, **save_kwargs) | ||
| encoded = base64.b64encode(buf.getvalue()).decode("ascii") | ||
| candidate = f"data:{out_mime};base64,{encoded}" | ||
| if len(candidate) <= max_base64_bytes: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This branch is stale against current main: the current helper also gates success on max_dimension via _dims_ok(...). Salvage should keep that dimension check while adding the image close/finally behavior. |
||
| logger.info("Auto-resized image fits: %.1f MB (quality=%s, %dx%d)", | ||
| len(candidate) / (1024 * 1024), q, | ||
| img.width, img.height) | ||
| return candidate | ||
|
|
||
| # If we still can't get it small enough, return the best attempt | ||
| # and let the caller decide | ||
| if candidate is not None: | ||
| logger.warning("Auto-resize could not fit image under %.1f MB (best: %.1f MB)", | ||
| max_base64_bytes / (1024 * 1024), len(candidate) / (1024 * 1024)) | ||
| return candidate | ||
|
|
||
| # Shouldn't reach here, but fall back to full encode | ||
| return data_url or _image_to_base64_data_url(image_path, mime_type=mime_type) | ||
| finally: | ||
| img.close() | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
|
|
||
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.
This catches malformed JSON after a successful urlopen, but 502/503 responses often raise HTTPError at urlopen before this line. If the goal is to return [] for transient HTML service failures, wrap urlopen too.