Skip to content

update bohrium-sdk version 0.6.0 #520

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 6 commits into
base: master
Choose a base branch
from

Conversation

dingzhaohan
Copy link
Contributor

@dingzhaohan dingzhaohan commented Jun 18, 2025

Summary by CodeRabbit

  • New Features

    • Added utility functions for creating and extracting zip files using standard Python tools.
  • Bug Fixes

    • Improved error handling for missing credentials by validating environment variables and profile settings.
  • Refactor

    • Updated integration to use the latest Bohrium SDK.
    • Replaced custom zip utilities with standard Python implementations for file compression and extraction.

dp-dingzhaohan and others added 2 commits June 18, 2025 16:34
for more information, see https://pre-commit.ci
Copy link
Contributor

coderabbitai bot commented Jun 18, 2025

📝 Walkthrough

Walkthrough

The updates transition the codebase from the older bohriumsdk to the new bohrium package, refactoring client and storage initialization to use explicit credential handling. Custom zip utility functions are introduced, replacing previous SDK utilities for zipping and unzipping files. Core logic for job upload, download, and submission remains otherwise unchanged.

Changes

File(s) Change Summary
dpdispatcher/contexts/openapi_context.py Replaced bohriumsdk imports with bohrium; added zip_file_list and unzip_file utilities; refactored credential handling and SDK initialization; updated job upload/download to use new zip utilities.
dpdispatcher/machines/openapi.py Updated imports to use bohrium; added unzip_file utility; refactored credential handling and SDK initialization; replaced SDK zip extraction utility with local implementation.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant User
    participant OpenAPIContext
    participant Bohrium
    participant Tiefblue

    User->>OpenAPIContext: Initialize(local_root, remote_profile)
    OpenAPIContext->>OpenAPIContext: Retrieve access_key, project_id, app_key
    OpenAPIContext->>Bohrium: Initialize(access_key, project_id, app_key)
    OpenAPIContext->>Tiefblue: Initialize()
Loading
sequenceDiagram
    participant User
    participant OpenAPIContext
    participant Tiefblue

    User->>OpenAPIContext: upload_job(job, common_files)
    OpenAPIContext->>OpenAPIContext: zip_file_list(...)
    OpenAPIContext->>Tiefblue: Upload zip archive
Loading
sequenceDiagram
    participant User
    participant OpenAPIContext
    participant Tiefblue

    User->>OpenAPIContext: download(submission)
    OpenAPIContext->>Tiefblue: Download zip archive
    OpenAPIContext->>OpenAPIContext: unzip_file(...)

📜 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 2f110f1 and 4271112.

📒 Files selected for processing (1)
  • dpdispatcher/contexts/openapi_context.py (5 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
dpdispatcher/contexts/openapi_context.py

[warning] 11-11: dpdispatcher/contexts/openapi_context.py#L11
Added line #L11 was not covered by tests


[warning] 17-17: dpdispatcher/contexts/openapi_context.py#L17
Added line #L17 was not covered by tests


[warning] 29-31: dpdispatcher/contexts/openapi_context.py#L29-L31
Added lines #L29 - L31 were not covered by tests


[warning] 35-35: dpdispatcher/contexts/openapi_context.py#L35
Added line #L35 was not covered by tests


[warning] 37-40: dpdispatcher/contexts/openapi_context.py#L37-L40
Added lines #L37 - L40 were not covered by tests


[warning] 42-48: dpdispatcher/contexts/openapi_context.py#L42-L48
Added lines #L42 - L48 were not covered by tests


[warning] 50-50: dpdispatcher/contexts/openapi_context.py#L50
Added line #L50 was not covered by tests


[warning] 52-55: dpdispatcher/contexts/openapi_context.py#L52-L55
Added lines #L52 - L55 were not covered by tests


[warning] 75-75: dpdispatcher/contexts/openapi_context.py#L75
Added line #L75 was not covered by tests


[warning] 80-80: dpdispatcher/contexts/openapi_context.py#L80
Added line #L80 was not covered by tests


[warning] 85-85: dpdispatcher/contexts/openapi_context.py#L85
Added line #L85 was not covered by tests


[warning] 90-91: dpdispatcher/contexts/openapi_context.py#L90-L91
Added lines #L90 - L91 were not covered by tests


[warning] 94-95: dpdispatcher/contexts/openapi_context.py#L94-L95
Added lines #L94 - L95 were not covered by tests


[warning] 98-98: dpdispatcher/contexts/openapi_context.py#L98
Added line #L98 was not covered by tests


[warning] 101-101: dpdispatcher/contexts/openapi_context.py#L101
Added line #L101 was not covered by tests


[warning] 156-156: dpdispatcher/contexts/openapi_context.py#L156
Added line #L156 was not covered by tests


[warning] 248-248: dpdispatcher/contexts/openapi_context.py#L248
Added line #L248 was not covered by tests

🪛 Pylint (3.3.7)
dpdispatcher/contexts/openapi_context.py

[refactor] 29-29: Consider using 'with' for resource-allocating operations

(R1732)


[refactor] 37-37: Consider using 'with' for resource-allocating operations

(R1732)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build (pbs)
  • GitHub Check: build (slurm)
🔇 Additional comments (5)
dpdispatcher/contexts/openapi_context.py (5)

1-1: LGTM - Import additions support new utility functions.

The added imports for glob and zipfile.ZipFile are necessary to support the new utility functions that replace the previous SDK utilities.

Also applies to: 5-5


10-17: LGTM - SDK migration imports updated correctly.

The imports have been correctly updated to use the new bohrium package and its resources (Bohrium, Job, Tiefblue) instead of the older bohriumsdk. The exception handling structure is preserved appropriately.


75-101: LGTM - Robust credential handling with proper validation.

The credential retrieval logic correctly prioritizes remote_profile values over environment variables, with appropriate fallbacks. The explicit validation and error messages for missing access_key and project_id provide clear feedback to users. The client and storage initialization using the new SDK API is implemented correctly.


156-156: LGTM - Function call updated correctly.

The call has been properly updated to use the new zip_file_list utility function instead of the previous Util.zip_file_list method.


248-248: LGTM - Function call updated correctly.

The call has been properly updated to use the new unzip_file utility function instead of the previous Util.unzip_file method.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment

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 auto-generate unit tests to generate unit tests for 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.

Sorry, something went wrong.

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: 3

🧹 Nitpick comments (2)
dpdispatcher/machines/openapi.py (1)

44-63: Credential lookup logic is solid – consider deduplicating & centralising

Nice explicit precedence (remote_profile → Bohrium-specific env → legacy env).
To avoid repetition across modules, you could move this snippet to a small credentials.py helper and re-use it here and in openapi_context.py.

dpdispatcher/contexts/openapi_context.py (1)

73-93: Credential retrieval duplicated – extract to helper or mixin

Exactly the same block exists in machines/openapi.py; factor it out to reduce maintenance cost and ensure consistent behaviour.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d55b3c3 and 0a81a19.

📒 Files selected for processing (2)
  • dpdispatcher/contexts/openapi_context.py (5 hunks)
  • dpdispatcher/machines/openapi.py (4 hunks)
🧰 Additional context used
🪛 Pylint (3.3.7)
dpdispatcher/machines/openapi.py

[refactor] 26-26: Consider using 'with' for resource-allocating operations

(R1732)

dpdispatcher/contexts/openapi_context.py

[refactor] 27-27: Consider using 'with' for resource-allocating operations

(R1732)


[refactor] 35-35: Consider using 'with' for resource-allocating operations

(R1732)

Comment on lines +25 to +30
def unzip_file(zip_file, out_dir="./"):
obj = ZipFile(zip_file, "r")
for item in obj.namelist():
obj.extract(item, out_dir)


Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use a context-manager & path-sanitisation in unzip_file

The helper leaks the ZipFile handle and is vulnerable to Zip-Slip because arbitrary paths from the archive are blindly extracted.

-def unzip_file(zip_file, out_dir="./"):
-    obj = ZipFile(zip_file, "r")
-    for item in obj.namelist():
-        obj.extract(item, out_dir)
+def unzip_file(zip_file, out_dir: str = "./"):
+    """Safely extract *zip_file* into *out_dir*, guarding against Zip-Slip."""
+    abs_out = os.path.abspath(out_dir)
+    with ZipFile(zip_file, "r") as zf:
+        for member in zf.namelist():
+            target = os.path.abspath(os.path.join(abs_out, member))
+            if not target.startswith(abs_out + os.sep):
+                raise ValueError(f"Unsafe path detected in zip: {member}")
+        zf.extractall(abs_out)

Closes the file handle automatically and blocks directory-traversal attacks.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def unzip_file(zip_file, out_dir="./"):
obj = ZipFile(zip_file, "r")
for item in obj.namelist():
obj.extract(item, out_dir)
def unzip_file(zip_file, out_dir: str = "./"):
"""Safely extract *zip_file* into *out_dir*, guarding against Zip-Slip."""
abs_out = os.path.abspath(out_dir)
with ZipFile(zip_file, "r") as zf:
for member in zf.namelist():
target = os.path.abspath(os.path.join(abs_out, member))
if not target.startswith(abs_out + os.sep):
raise ValueError(f"Unsafe path detected in zip: {member}")
zf.extractall(abs_out)
🧰 Tools
🪛 Pylint (3.3.7)

[refactor] 26-26: Consider using 'with' for resource-allocating operations

(R1732)

🤖 Prompt for AI Agents
In dpdispatcher/machines/openapi.py around lines 25 to 30, the unzip_file
function currently opens a ZipFile without using a context manager, causing a
file handle leak, and extracts files without sanitizing paths, making it
vulnerable to Zip-Slip attacks. Fix this by using a with statement to open the
ZipFile, ensuring it closes automatically, and sanitize each extracted file path
to prevent directory traversal before extraction.

Comment on lines +26 to +30
def unzip_file(zip_file, out_dir="./"):
obj = ZipFile(zip_file, "r")
for item in obj.namelist():
obj.extract(item, out_dir)

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

Same Zip concerns as in machines/openapi.py

Replicate the safer, context-managed implementation suggested earlier to avoid handle leaks and Zip-Slip.

🧰 Tools
🪛 Pylint (3.3.7)

[refactor] 27-27: Consider using 'with' for resource-allocating operations

(R1732)

🤖 Prompt for AI Agents
In dpdispatcher/contexts/openapi_context.py around lines 26 to 30, the
unzip_file function opens the ZipFile without using a context manager and
extracts files without validating paths, risking resource leaks and Zip-Slip
attacks. Refactor the function to use a with statement to open the ZipFile,
ensuring it is properly closed, and add path validation to prevent extraction
outside the target directory, mitigating Zip-Slip vulnerabilities.

Comment on lines +32 to +53
def zip_file_list(root_path, zip_filename, file_list=[]):
out_zip_file = os.path.join(root_path, zip_filename)
# print('debug: file_list', file_list)
zip_obj = ZipFile(out_zip_file, "w")
for f in file_list:
matched_files = os.path.join(root_path, f)
for ii in glob.glob(matched_files):
# print('debug: matched_files:ii', ii)
if os.path.isdir(ii):
arcname = os.path.relpath(ii, start=root_path)
zip_obj.write(ii, arcname)
for root, dirs, files in os.walk(ii):
for file in files:
filename = os.path.join(root, file)
arcname = os.path.relpath(filename, start=root_path)
# print('debug: filename:arcname:root_path', filename, arcname, root_path)
zip_obj.write(filename, arcname)
else:
arcname = os.path.relpath(ii, start=root_path)
zip_obj.write(ii, arcname)
zip_obj.close()
return out_zip_file
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

zip_file_list – avoid mutable default & close the archive properly

Two issues:

  1. file_list=[] is a mutable default shared between calls.
  2. ZipFile is not used in a with block; handle remains open on exceptions.
-from zipfile import ZipFile
+from zipfile import ZipFile, ZIP_DEFLATED
@@
-def zip_file_list(root_path, zip_filename, file_list=[]):
+def zip_file_list(root_path, zip_filename, file_list=None):
+    if file_list is None:
+        file_list = []
@@
-    zip_obj = ZipFile(out_zip_file, "w")
-    for f in file_list:
+    with ZipFile(out_zip_file, "w", compression=ZIP_DEFLATED) as zip_obj:
+        for f in file_list:
@@
-                zip_obj.write(ii, arcname)
-    zip_obj.close()
-    return out_zip_file
+                zip_obj.write(ii, arcname)
+    return out_zip_file

This removes the shared-state bug, guarantees the file is flushed/closed, and activates compression for a smaller upload.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def zip_file_list(root_path, zip_filename, file_list=[]):
out_zip_file = os.path.join(root_path, zip_filename)
# print('debug: file_list', file_list)
zip_obj = ZipFile(out_zip_file, "w")
for f in file_list:
matched_files = os.path.join(root_path, f)
for ii in glob.glob(matched_files):
# print('debug: matched_files:ii', ii)
if os.path.isdir(ii):
arcname = os.path.relpath(ii, start=root_path)
zip_obj.write(ii, arcname)
for root, dirs, files in os.walk(ii):
for file in files:
filename = os.path.join(root, file)
arcname = os.path.relpath(filename, start=root_path)
# print('debug: filename:arcname:root_path', filename, arcname, root_path)
zip_obj.write(filename, arcname)
else:
arcname = os.path.relpath(ii, start=root_path)
zip_obj.write(ii, arcname)
zip_obj.close()
return out_zip_file
from zipfile import ZipFile, ZIP_DEFLATED
import os
import glob
def zip_file_list(root_path, zip_filename, file_list=None):
if file_list is None:
file_list = []
out_zip_file = os.path.join(root_path, zip_filename)
with ZipFile(out_zip_file, "w", compression=ZIP_DEFLATED) as zip_obj:
for f in file_list:
matched_files = os.path.join(root_path, f)
for ii in glob.glob(matched_files):
if os.path.isdir(ii):
arcname = os.path.relpath(ii, start=root_path)
zip_obj.write(ii, arcname)
for root, dirs, files in os.walk(ii):
for file in files:
filename = os.path.join(root, file)
arcname = os.path.relpath(filename, start=root_path)
zip_obj.write(filename, arcname)
else:
arcname = os.path.relpath(ii, start=root_path)
zip_obj.write(ii, arcname)
return out_zip_file
🧰 Tools
🪛 Pylint (3.3.7)

[refactor] 35-35: Consider using 'with' for resource-allocating operations

(R1732)

🤖 Prompt for AI Agents
In dpdispatcher/contexts/openapi_context.py around lines 32 to 53, the function
zip_file_list uses a mutable default argument file_list=[] which can cause
shared state bugs across calls, and it opens the ZipFile without a with
statement, risking the file not being closed properly on exceptions. To fix
this, change the default value of file_list to None and initialize it to an
empty list inside the function if None. Also, open the ZipFile using a with
statement to ensure it is properly closed after writing, and enable compression
by specifying the compression mode when creating the ZipFile.

dp-dingzhaohan and others added 3 commits June 20, 2025 14:17
for more information, see https://pre-commit.ci
@njzjz njzjz closed this Jun 24, 2025
@njzjz njzjz reopened this Jun 24, 2025
Copy link

codecov bot commented Jun 24, 2025

Codecov Report

Attention: Patch coverage is 17.54386% with 47 lines in your changes missing coverage. Please review.

Project coverage is 47.42%. Comparing base (d55b3c3) to head (4271112).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
dpdispatcher/contexts/openapi_context.py 17.50% 33 Missing ⚠️
dpdispatcher/machines/openapi.py 17.64% 14 Missing ⚠️

❗ There is a different number of reports uploaded between BASE (d55b3c3) and HEAD (4271112). Click for more details.

HEAD has 1 upload less than BASE
Flag BASE (d55b3c3) HEAD (4271112)
15 14
Additional details and impacted files
@@             Coverage Diff             @@
##           master     #520       +/-   ##
===========================================
- Coverage   60.16%   47.42%   -12.74%     
===========================================
  Files          39       39               
  Lines        3863     3903       +40     
===========================================
- Hits         2324     1851      -473     
- Misses       1539     2052      +513     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
Copy link
Member

@njzjz njzjz left a comment

Choose a reason for hiding this comment

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

I print the detailed error in the unit test, and it is ModuleNotFoundError: No module named 'httpx'

ERROR: test_failed_submission (tests.test_run_submission_bohrium.TestOpenAPIRun.test_failed_submission)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/work/dpdispatcher/dpdispatcher/dpdispatcher/contexts/openapi_context.py", line 10, in <module>
    from bohrium import Bohrium
  File "/opt/hostedtoolcache/Python/3.12.10/x64/lib/python3.12/site-packages/bohrium/__init__.py", line 1, in <module>
    from ._client import Bohrium, AsyncBohrium
  File "/opt/hostedtoolcache/Python/3.12.10/x64/lib/python3.12/site-packages/bohrium/_client.py", line 6, in <module>
    from httpx import URL, Client, Response, Timeout
ModuleNotFoundError: No module named 'httpx'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/runner/work/dpdispatcher/dpdispatcher/tests/test_run_submission.py", line 128, in test_failed_submission
    machine = Machine.load_from_dict(self.machine_dict)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/runner/work/dpdispatcher/dpdispatcher/dpdispatcher/machine.py", line 150, in load_from_dict
    context = BaseContext.load_from_dict(machine_dict)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/runner/work/dpdispatcher/dpdispatcher/dpdispatcher/base_context.py", line [45](https://github.com/deepmodeling/dpdispatcher/actions/runs/15847376562/job/44672576823?pr=520#step:6:46), in load_from_dict
    context = context_class.load_from_dict(context_dict)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/runner/work/dpdispatcher/dpdispatcher/dpdispatcher/contexts/openapi_context.py", line 111, in load_from_dict
    bohrium_context = cls(
                      ^^^^
  File "/home/runner/work/dpdispatcher/dpdispatcher/dpdispatcher/contexts/openapi_context.py", line 68, in __init__
    raise ModuleNotFoundError(
ModuleNotFoundError: bohriumsdk not installed. Install dpdispatcher with `pip install dpdispatcher[bohrium]`

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

Successfully merging this pull request may close these issues.

None yet

3 participants