Skip to content

Conversation

fm3
Copy link
Member

@fm3 fm3 commented Jan 29, 2025

  • Fixes a bug in the migration: for editable mapping updates, set actionTracingId to tracingid rather than (old) mappingId
  • Adds a script that scans an old fossildb for necessary renamings
  • Adds a script that applies such renamings to a new fossildb

Example file for id mapping (annotationId: → (mappingId → tracingId)):

{
    "679b5691d10000ac0632e1ae":
    {
        "6b70de43-9e2c-4c6e-ae52-e64d7be59d20": "newId"
    },
    "679b5684d10000100632e1ab":
    {
        "a82680ea-1f16-4f55-ad96-a2d7ba46e90b": "newId2"
    }
}

@fm3 fm3 self-assigned this Jan 29, 2025
Copy link
Contributor

coderabbitai bot commented Jan 29, 2025

Warning

Rate limit exceeded

@fm3 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 34 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c34947f and dbbc9a7.

📒 Files selected for processing (1)
  • tools/migration-unified-annotation-versioning/repair_editable_mapping_updates.py (1 hunks)
📝 Walkthrough

Walkthrough

This pull request introduces changes to the migration and annotation versioning tools. A new script find_mapping_tracing_mapping.py is added to generate mappings between tracing IDs and editable mapping IDs by connecting to FossilDB and PostgreSQL databases. The migration.py file is updated with a modified method signature for fetch_updates, explicitly separating tracing and mapping IDs. A complementary script repair_editable_mapping_updates.py is created to repair and update annotation records in FossilDB based on the generated mapping.

Changes

File Change Summary
.gitignore Added mapping_tracing_mapping.json to ignored files
find_mapping_tracing_mapping.py New script to generate tracing ID to editable mapping ID mappings
migration.py Updated fetch_updates method signature to include separate tracing ID parameter
repair_editable_mapping_updates.py New script to repair and update annotation records in FossilDB

Suggested labels

bug, backend

Suggested reviewers

  • daniel-wer

Poem

🐰 Mapping traces with care and might,
Through databases, our rabbit takes flight!
IDs dancing, versions align,
A migration script, simply divine!
Hop, hop, data's journey bright! 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

@fm3 fm3 marked this pull request as ready for review January 30, 2025 10:53
@fm3 fm3 requested a review from normanrz January 30, 2025 10:53
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: 0

🧹 Nitpick comments (6)
tools/migration-unified-annotation-versioning/find_mapping_tracing_mapping.py (2)

16-46: Add error handling for file operations and make the output file configurable.

Consider the following improvements:

  1. Add error handling for file operations to handle potential I/O errors.
  2. Make the output file path configurable via command-line arguments.

Apply this diff to implement the suggestions:

 def main():
     logger.info("Hello from find_mapping_tracing_mapping")
     setup_logging()
     parser = argparse.ArgumentParser()
     parser.add_argument("--src", type=str, help="Source fossildb host and port. Example: localhost:7155", required=True)
     parser.add_argument("--postgres", help="Postgres connection specifier, default is postgresql://postgres@localhost:5432/webknossos", type=str, default="postgresql://postgres@localhost:5432/webknossos")
+    parser.add_argument("--output", help="Output file path for the mapping JSON", type=str, default="mapping_tracing_mapping.json")
     args = parser.parse_args()
     before = time.time()
     annotations = read_annotation_list(args)
     src_stub = connect_to_fossildb(args.src, "source")
     mappings = {}
     for annotation in annotations:
         annotation_id = annotation["_id"]
         id_mapping_for_annotation = {}
         for tracing_id, layer_type in annotation["layers"].items():
             if layer_type == 'Volume':
                 try:
                     editable_mapping_id = get_editable_mapping_id(src_stub, tracing_id, layer_type)
                     if editable_mapping_id is not None:
                         id_mapping_for_annotation[editable_mapping_id] = tracing_id
                 except Exception as e:
                     logger.info(f"exception while checking layer {tracing_id} of {annotation_id}: {e}")
         if id_mapping_for_annotation:
             mappings[annotation_id] = id_mapping_for_annotation

-    outfile_name = "mapping_tracing_mapping.json"
-    logger.info(f"Writing mapping to {outfile_name}...")
-    with open(outfile_name, "wb") as outfile:
-        outfile.write(msgspec.json.encode(mappings))
+    try:
+        logger.info(f"Writing mapping to {args.output}...")
+        with open(args.output, "wb") as outfile:
+            outfile.write(msgspec.json.encode(mappings))
+    except IOError as e:
+        logger.error(f"Failed to write mapping to {args.output}: {e}")
+        sys.exit(1)

-    log_since(before, f"Wrote full id mapping to {outfile_name}. Checked {len(annotations)} annotations, wrote {len(mappings)} annotation id mappings.")
+    log_since(before, f"Wrote full id mapping to {args.output}. Checked {len(annotations)} annotations, wrote {len(mappings)} annotation id mappings.")

70-88: Remove unnecessary f-string prefixes.

The SQL queries don't use any f-string interpolation.

Apply this diff to fix the f-string usage:

-    cursor.execute(f"SELECT COUNT(*) FROM webknossos.annotations")
+    cursor.execute("SELECT COUNT(*) FROM webknossos.annotations")

-    query = f"""SELECT
+    query = """SELECT
                  a._id,
                  JSON_OBJECT_AGG(al.tracingId, al.typ) AS layers,
                  JSON_OBJECT_AGG(al.tracingId, al.name) AS layerNames
                FROM webknossos.annotation_layers al
                JOIN webknossos.annotations a on al._annotation = a._id
                GROUP BY a._id
                """
🧰 Tools
🪛 Ruff (0.8.2)

74-74: f-string without any placeholders

Remove extraneous f prefix

(F541)


77-84: f-string without any placeholders

Remove extraneous f prefix

(F541)

tools/migration-unified-annotation-versioning/repair_editable_mapping_updates.py (4)

13-30: Simplify dictionary key iteration.

The .keys() method call is unnecessary when iterating over dictionary keys.

Apply this diff to simplify the code:

-        for annotation_id in id_mapping.keys():
+        for annotation_id in id_mapping:
🧰 Tools
🪛 Ruff (0.8.2)

27-27: Use key in dict instead of key in dict.keys()

Remove .keys()

(SIM118)


33-66: Consider breaking down the function for better maintainability.

The function has multiple responsibilities:

  1. Processing updates in batches
  2. Updating the actionTracingId
  3. Managing the put buffer

Consider extracting the update processing logic into a separate function.

Apply this diff to refactor the code:

+def process_update_group(update_group: dict, id_mapping_for_annotation: dict) -> Tuple[bool, int]:
+    group_changed = False
+    changed_update_count = 0
+    for update in update_group:
+        if "value" in update:
+            update_value = update["value"]
+            if "actionTracingId" in update_value and update_value["actionTracingId"] in id_mapping_for_annotation:
+                update_value["actionTracingId"] = id_mapping_for_annotation[update_value["actionTracingId"]]
+                group_changed = True
+                changed_update_count += 1
+    return group_changed, changed_update_count
+
 def repair_updates_of_annotation(stub, annotation_id, id_mapping_for_annotation, json_encoder, json_decoder):
     get_batch_size = 100  # in update groups
     put_buffer_size = 100  # in update groups
 
     before = time.time()
     put_buffer = []
     changed_update_count = 0
     newest_version = get_newest_version(stub, annotation_id, "annotationUpdates")
     if newest_version > 10000:
         logger.info(f"Newest version of {annotation_id} is {newest_version}. This may take some time...")
     for batch_start, batch_end in reversed(list(batch_range(newest_version + 1, get_batch_size))):
         update_groups_batch = get_update_batch(stub, annotation_id, batch_start, batch_end - 1)
         for version, update_group_bytes in update_groups_batch:
             update_group = json_decoder.decode(update_group_bytes)
-            group_changed = False
-            for update in update_group:
-                if "value" in update:
-                    update_value = update["value"]
-                    if "actionTracingId" in update_value and update_value["actionTracingId"] in id_mapping_for_annotation:
-                        update_value["actionTracingId"] = id_mapping_for_annotation[update_value["actionTracingId"]]
-                        group_changed = True
-                        changed_update_count += 1
+            group_changed, group_changed_count = process_update_group(update_group, id_mapping_for_annotation)
+            changed_update_count += group_changed_count
             if group_changed:
                 versioned_key_value_pair = proto.VersionedKeyValuePairProto()
                 versioned_key_value_pair.key = annotation_id
                 versioned_key_value_pair.version = version
                 versioned_key_value_pair.value = json_encoder.encode(update_group)
                 put_buffer.append(versioned_key_value_pair)
                 if len(put_buffer) >= put_buffer_size:
                     put_multiple_keys_versions(stub, "annotationUpdates", put_buffer)
                     put_buffer = []
     if len(put_buffer) > 0:
         put_multiple_keys_versions(stub, "annotationUpdates", put_buffer)
     log_since(before, f"Repaired {changed_update_count} updates of annotation {annotation_id},")

33-66: Consider parameterizing batch sizes.

The batch sizes are currently hardcoded. Consider making them configurable via command line arguments for better flexibility in different environments.

 def main():
     parser = argparse.ArgumentParser()
     parser.add_argument("--fossil", type=str, help="Fossildb host and port. Example: localhost:7155", required=True)
     parser.add_argument("--id_mapping", type=str, help="json file containing the id mapping determined by find_mapping_tracing_mapping.py", required=True)
+    parser.add_argument("--get_batch_size", type=int, help="Batch size for get operations", default=100)
+    parser.add_argument("--put_batch_size", type=int, help="Batch size for put operations", default=100)
     args = parser.parse_args()

 def repair_updates_of_annotation(stub, annotation_id, id_mapping_for_annotation, json_encoder, json_decoder):
-    get_batch_size = 100  # in update groups
-    put_buffer_size = 100  # in update groups
+    get_batch_size = args.get_batch_size  # in update groups
+    put_buffer_size = args.put_batch_size  # in update groups

84-90: Consider using consistent error handling.

Other functions use assert_grpc_success, but this one only checks the success flag. Consider using the same error handling pattern for consistency.

 def get_newest_version(stub, tracing_id: str, collection: str) -> int:
     getReply = stub.Get(
         proto.GetRequest(collection=collection, key=tracing_id, mayBeEmpty=True)
     )
+    assert_grpc_success(getReply)
     if getReply.success:
         return getReply.actualVersion
     return 0
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a46d76b and c34947f.

📒 Files selected for processing (4)
  • tools/migration-unified-annotation-versioning/.gitignore (1 hunks)
  • tools/migration-unified-annotation-versioning/find_mapping_tracing_mapping.py (1 hunks)
  • tools/migration-unified-annotation-versioning/migration.py (5 hunks)
  • tools/migration-unified-annotation-versioning/repair_editable_mapping_updates.py (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tools/migration-unified-annotation-versioning/.gitignore
🧰 Additional context used
🪛 Ruff (0.8.2)
tools/migration-unified-annotation-versioning/find_mapping_tracing_mapping.py

74-74: f-string without any placeholders

Remove extraneous f prefix

(F541)


77-84: f-string without any placeholders

Remove extraneous f prefix

(F541)

tools/migration-unified-annotation-versioning/repair_editable_mapping_updates.py

27-27: Use key in dict instead of key in dict.keys()

Remove .keys()

(SIM118)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: circleci_build
🔇 Additional comments (12)
tools/migration-unified-annotation-versioning/find_mapping_tracing_mapping.py (2)

49-54: LGTM!

The function is well-implemented with proper error handling and type hints.


57-67: LGTM!

The function is well-implemented with proper type hints and handles all edge cases correctly.

tools/migration-unified-annotation-versioning/repair_editable_mapping_updates.py (6)

69-71: LGTM!

The function is well-implemented with proper type hints and error handling.


74-81: LGTM!

The function is well-implemented with proper type hints and correctly handles the order of versions and values.


84-90: LGTM!

The function is well-implemented with proper type hints and handles empty responses correctly.


13-30: LGTM! Well-structured main function.

The function properly handles command line arguments, sets up logging, and uses context managers for file handling.

🧰 Tools
🪛 Ruff (0.8.2)

27-27: Use key in dict instead of key in dict.keys()

Remove .keys()

(SIM118)


69-71: LGTM! Proper error handling.

The function correctly handles gRPC calls and uses assertions to verify success.


74-81: LGTM! Well-implemented batch retrieval.

The function correctly handles gRPC calls, error checking, and maintains chronological order.

tools/migration-unified-annotation-versioning/migration.py (4)

108-108: LGTM!

The method signature change improves clarity by explicitly separating tracing_id and tracing_or_mapping_id parameters.


242-242: LGTM!

The change correctly sets actionTracingId to tracing_id for both volume layers and their corresponding mappings, as explained in the comment.


Line range hint 108-128: LGTM! Improved method signature.

The updated signature correctly separates tracing_id and tracing_or_mapping_id, aligning with the PR objectives.


242-242: LGTM! Bug fix for actionTracingId.

The code now correctly uses tracing_id for actionTracingId, even for mappings, fixing the reported bug.

@fm3 fm3 enabled auto-merge (squash) January 30, 2025 11:21
@fm3 fm3 merged commit 2171b8f into master Jan 30, 2025
3 checks passed
@fm3 fm3 deleted the mappingid-tracingid branch January 30, 2025 11:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants