Skip to content

Truncate action log to avoid json string decoding overflow #8757

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
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

MichaelBuessemeyer
Copy link
Contributor

This PR introduces a new truncate url param to the update actions log route. If set to true (default should be false), the backend sends the a max of 1000 update actions per update group. The goal is to reduce the max possible string length of the json encoded update actions to not hit the limit of the frontend. See #8594 for more details.

URL of deployed dev instance (used for testing):

  • https://___.webknossos.xyz

Steps to test:

  • I suggest testing locally.
  • Open TSAnnotationService and set maxUpdateActionLogBatchSize = 3 or so.
  • Open an annotation and annotate buckets multiple times with multiple strokes
  • Save
  • Open the version restore view. Some version numbers should be missing as they got truncated away. At most maxUpdateActionLogBatchSize consecutive update actions should be listed.

TODOs:

  • confirm whether that's actually what we want.

Issues:


(Please delete unneeded items, merge only when none are left open)

  • Added changelog entry (create a $PR_NUMBER.md file in unreleased_changes or use ./tools/create-changelog-entry.py)

Copy link
Contributor

coderabbitai bot commented Jul 7, 2025

📝 Walkthrough

"""

Walkthrough

A new truncate query parameter was introduced to the update action log API, allowing truncation of update action groups to a maximum of 1000 items when enabled. This involved changes to the backend service, controller, and routing, as well as frontend logic to always request truncation.

Changes

Files/Paths Change Summary
frontend/javascripts/admin/rest_api.ts Added optional truncateActionLog parameter to getUpdateActionLog; includes truncate query parameter in URL.
frontend/javascripts/viewer/view/version_list.tsx Modified call to getUpdateActionLog to pass true for truncation argument.
.../TSAnnotationService.scala Added truncate parameter to updateActionLog; truncates update action groups to max 1000 items if true.
.../TSAnnotationController.scala, .../tracingstore.latest.routes Added optional truncate parameter to controller method and route for update action log endpoint.

Assessment against linked issues

Objective Addressed Explanation
Truncate update action log groups to first 1000 items for version restore view (#8594)
Add truncate query parameter to update action log API and propagate through backend (#8594)
Update frontend to always request truncation for update action log in version restore view (#8594)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes were found.

Poem

In the meadow of code, the logs grew too tall,
So I nibbled them down, a thousand in all.
With a hop and a skip, I trimmed every batch,
Now version restores are quick to dispatch!
🐇✨
No more crashes or endless scroll,
Just concise logs—now under control!
"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3b289d3 and 3cd88f8.

📒 Files selected for processing (2)
  • frontend/javascripts/admin/rest_api.ts (1 hunks)
  • frontend/javascripts/viewer/view/version_list.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/javascripts/admin/rest_api.ts
🧰 Additional context used
🧠 Learnings (1)
frontend/javascripts/viewer/view/version_list.tsx (1)
Learnt from: dieknolle3333
PR: scalableminds/webknossos#8168
File: frontend/javascripts/oxalis/model/sagas/proofread_saga.ts:1039-1039
Timestamp: 2024-11-22T17:18:04.217Z
Learning: In `frontend/javascripts/oxalis/model/sagas/proofread_saga.ts`, when calling `getMagInfo`, the use of `volumeTracingLayer.resolutions` is intentional and should not be changed to `volumeTracingLayer.mags`.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: frontend-tests
  • GitHub Check: build-smoketest-push
  • GitHub Check: backend-tests
🔇 Additional comments (1)
frontend/javascripts/viewer/view/version_list.tsx (1)

171-171: LGTM! Hardcoding truncation as a safety measure.

Adding true as the fifth parameter correctly enables the new truncateActionLog flag. Hardcoding this to true is appropriate since truncation serves as a safety measure to prevent JSON string decoding overflow (as mentioned in the PR objectives), rather than being a user-configurable feature.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 14dbb8a and 3b289d3.

📒 Files selected for processing (4)
  • frontend/javascripts/admin/rest_api.ts (1 hunks)
  • webknossos-tracingstore/app/com/scalableminds/webknossos/tracingstore/annotation/TSAnnotationService.scala (3 hunks)
  • webknossos-tracingstore/app/com/scalableminds/webknossos/tracingstore/controllers/TSAnnotationController.scala (1 hunks)
  • webknossos-tracingstore/conf/tracingstore.latest.routes (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
webknossos-tracingstore/app/com/scalableminds/webknossos/tracingstore/annotation/TSAnnotationService.scala (1)
Learnt from: MichaelBuessemeyer
PR: scalableminds/webknossos#8236
File: webknossos-datastore/app/com/scalableminds/webknossos/datastore/datareaders/precomputed/NeuroglancerPrecomputedShardingUtils.scala:23-28
Timestamp: 2025-04-25T11:06:13.275Z
Learning: AlfuCache in the WebKnossos codebase has default configured TTL (time-to-live) and size limits, providing automatic protection against unbounded memory growth.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: backend-tests
  • GitHub Check: build-smoketest-push
  • GitHub Check: frontend-tests
🔇 Additional comments (5)
frontend/javascripts/admin/rest_api.ts (1)

782-782: LGTM! Clean implementation of the truncate parameter.

The hardcoded "true" value ensures the frontend always requests truncated results to prevent JSON decoding overflow, which aligns with the PR objectives.

Consider making this configurable in the future if there's a need to conditionally disable truncation:

-    const params = new URLSearchParams([["truncate", "true"]]);
+    const params = new URLSearchParams([["truncate", truncate?.toString() ?? "true"]]);

However, for the current use case where preventing overflow is critical, the hardcoded approach is appropriate.

webknossos-tracingstore/conf/tracingstore.latest.routes (1)

10-10: LGTM! Correct route parameter addition.

The truncate: Option[Boolean] parameter is properly added to the route definition, maintaining backward compatibility with the optional type.

webknossos-tracingstore/app/com/scalableminds/webknossos/tracingstore/annotation/TSAnnotationService.scala (2)

63-63: Good addition of configuration constant.

The maxUpdateActionLogBatchSize constant provides a clear, configurable limit for truncation and improves code maintainability.


245-246: Clean method signature update.

The addition of the truncate parameter is well-named and appropriately typed for controlling the truncation behavior.

webknossos-tracingstore/app/com/scalableminds/webknossos/tracingstore/controllers/TSAnnotationController.scala (1)

79-94: Well-implemented parameter addition with backward compatibility.

The optional truncate parameter is properly handled with sensible defaults and maintains backward compatibility. The implementation follows the established pattern for optional parameters in this method.

Comment on lines +263 to +265
truncatedUpdateActionBatches = if (truncate) updateActionBatches.map(_.take(maxUpdateActionLogBatchSize))
else updateActionBatches
} yield Json.toJson(truncatedUpdateActionBatches.flatten.map(versionedTupleToJson))
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider total response size in addition to per-batch truncation.

The current implementation truncates each batch to 1000 items but then flattens all batches together. This could still result in very large JSON responses if there are many batches, potentially not fully addressing the JSON decoding overflow issue.

Consider also limiting the total number of batches or implementing a global response size limit to ensure the final JSON stays within frontend decoding limits.

 truncatedUpdateActionBatches = if (truncate) updateActionBatches.map(_.take(maxUpdateActionLogBatchSize))
 else updateActionBatches
+// Consider also limiting total response size:
+finalBatches = if (truncate) truncatedUpdateActionBatches.take(maxBatchCount) else truncatedUpdateActionBatches
-} yield Json.toJson(truncatedUpdateActionBatches.flatten.map(versionedTupleToJson))
+} yield Json.toJson(finalBatches.flatten.map(versionedTupleToJson))

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In
webknossos-tracingstore/app/com/scalableminds/webknossos/tracingstore/annotation/TSAnnotationService.scala
around lines 263 to 265, the code truncates each batch to a maximum size but
then flattens all batches, which can still produce an excessively large JSON
response. To fix this, implement an additional limit on the total number of
batches or the overall size of the combined response before converting to JSON,
ensuring the final output stays within frontend decoding limits.

@MichaelBuessemeyer
Copy link
Contributor Author

MichaelBuessemeyer commented Jul 7, 2025

@fm3 @philippotto

Ok I am questioning myself right now whether what I implemented is actually what was suggested in the issue / a solution to the problem:

I suggest to add an optional truncate field to the update action log route. If it's true, no more than 1000 items in an action group will be output.

I am not sure whether the concept really exists in the backend route offering the update action log. The backend loads something like Array[Array[UpdateAction]] from the fossil db and the inner Array[UpdateAction] very likely seems to be an update action group.

My question / thought now: But what happens in case of a having a lot of update action groups with each having 1000 update actions. Doesn't this maybe also blow up the json serialized string to not fit into the frontend max buffer or so? So shouldn't we keep the limit to the total sum of update actions? Or is this too unrealistic to blow up the max string length in case of "only" 1000 update actions per update action group

Edit: Coderabbit also mentioned my thoughts: #8757 (comment)

@fm3
Copy link
Member

fm3 commented Jul 7, 2025

Maybe the outer array size is limited by the pagination parameters?

@MichaelBuessemeyer
Copy link
Contributor Author

Maybe the outer array size is limited by the pagination parameters?

yeah right, it seems like 2500 is the current max of versions per request 🤔 This should kinda be a outer level restriction, limiting the update actions max in total per request.

The code says:

// This used to be 5000 but we had logs where lots of UPDATE_BUCKET
// update actions existed in one batch. The JSON payload exceeded a length
// of 2**29 which led to an empty JSON string because of maximum string length
// limits by the node engine.
// Therefore, the value was halved for now.

Should I restore the old limit @philippotto 🤔?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Truncate group with updateBucket actions in version restore view
2 participants