Skip to content
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

Update fix/clean up #4292

Merged
merged 6 commits into from
Jan 27, 2025

Conversation

NicholasTurner23
Copy link
Contributor

@NicholasTurner23 NicholasTurner23 commented Jan 27, 2025

Description

Enable task retries for weather data.

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Improved error handling in API methods with more descriptive logging.
    • Enhanced input validation for site updates.
  • Refactor

    • Updated BigQuery table references in data loading workflows.
    • Standardized Airflow task decorators with improved error handling and context management.
    • Enhanced data cleaning process for low-cost sensor data.
  • Documentation

    • Added deprecation note for Airclouds feature.

The changes focus on improving code reliability, error handling, and workflow consistency across various data processing components.

Copy link
Contributor

coderabbitai bot commented Jan 27, 2025

📝 Walkthrough

Walkthrough

The pull request introduces refinements to exception handling, method signatures, and Airflow DAG configurations across multiple files. The changes focus on improving error logging, input validation, and task execution robustness in the AirQo ETL (Extract, Transform, Load) workflows. Key modifications include updating the update_sites method with stricter type hints, adding more descriptive exception messages, and enhancing Airflow task decorators with retry mechanisms and context management.

Changes

File Change Summary
src/workflows/airqo_etl_utils/airqo_api.py - Enhanced exception handling in get_meta_data with more descriptive logging
- Updated update_sites method signature with type hints and docstring
- Added input validation for site dictionaries
src/workflows/airqo_etl_utils/meta_data_utils.py - Added comment indicating "Airclouds are deprecated"
src/workflows/dags/meta_data.py - Updated BigQuery table references from *_*_table to *_table
src/workflows/dags/weather_measurements.py - Added provide_context=True to various extract methods
- Implemented retries and retry_delay for load tasks
- Standardized task decorator configurations
src/workflows/airqo_etl_utils/airqo_utils.py - Expanded docstring and enhanced error handling in clean_low_cost_sensor_data method

Possibly related PRs

  • Update fix/clean up #3616: Changes in src/workflows/airqo_etl_utils/airqo_api.py related to method signatures and type annotations may connect with the modifications in the update_sites method in the main PR, as both involve enhancing method signatures and improving clarity.
  • Clean up/Sanitize #3782: The updates to the get_meta_data method in src/workflows/airqo_etl_utils/airqo_api.py include enhanced error handling, which aligns with the changes made to exception handling in the get_meta_data method in the main PR.
  • Update fix/pipeline task retries #3786: The modifications to the get_devices method in src/workflows/airqo_etl_utils/airqo_utils.py that enhance validation logic may relate to the stricter input validation introduced in the update_sites method of the main PR.

Suggested Reviewers

  • Baalmart
  • BenjaminSsempala
  • Psalmz777

Poem

🌟 Workflows dancing, code refined,
Error handling now intertwined,
Retry and context, a developer's art,
Airflow tasks with a smarter start!
ETL magic, clean and bright 🚀

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

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

🧹 Nitpick comments (2)
src/workflows/airqo_etl_utils/airqo_utils.py (2)

512-512: Address the TODO comment regarding raw data quality checks.

The comment indicates a need for a more structured approach to raw data quality checks.

Would you like me to help design a more robust implementation for the raw data quality checks?


513-520: Consider adding error handling to the pattern matching block.

While the pattern matching implementation is clean, it would benefit from error handling to gracefully handle unexpected device categories.

 match device_category:
     case DeviceCategory.LOW_COST_GAS:
-        AirQoGxExpectations.from_pandas().gaseous_low_cost_sensor_raw_data_check(
-            data
-        )
+        try:
+            AirQoGxExpectations.from_pandas().gaseous_low_cost_sensor_raw_data_check(
+                data
+            )
+        except Exception as e:
+            logger.warning(f"Raw data quality check failed for LOW_COST_GAS: {e}")
     case DeviceCategory.LOW_COST:
-        AirQoGxExpectations.from_pandas().pm2_5_low_cost_sensor_raw_data(data)
+        try:
+            AirQoGxExpectations.from_pandas().pm2_5_low_cost_sensor_raw_data(data)
+        except Exception as e:
+            logger.warning(f"Raw data quality check failed for LOW_COST: {e}")
+    case _:
+        logger.warning(f"Unexpected device category: {device_category}")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ad57cab and 5b8c250.

📒 Files selected for processing (1)
  • src/workflows/airqo_etl_utils/airqo_utils.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
src/workflows/airqo_etl_utils/airqo_utils.py

525-525: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
src/workflows/airqo_etl_utils/airqo_utils.py (1)

488-507: Well-documented function with clear steps!

The expanded docstring provides excellent clarity about the function's purpose and process. The step-by-step breakdown and proper type hints make it very maintainable.

Comment on lines +520 to +525
try:
data.dropna(subset=["timestamp"], inplace=True)
data["timestamp"] = pd.to_datetime(data["timestamp"])
data.dropna(subset=["timestamp"], inplace=True)
except Exception as e:
logger.exception(f"There is an issue with the timestamp column: {e}")
raise KeyError(f"An error has occurred with the 'timestamp' column: {e}")
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

Improve exception handling by using raise from.

The current exception handling could be improved to better preserve the exception chain.

 try:
     data.dropna(subset=["timestamp"], inplace=True)
     data["timestamp"] = pd.to_datetime(data["timestamp"])
 except Exception as e:
     logger.exception(f"There is an issue with the timestamp column: {e}")
-    raise KeyError(f"An error has occurred with the 'timestamp' column: {e}")
+    raise KeyError(f"An error has occurred with the 'timestamp' column: {e}") from e
📝 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
try:
data.dropna(subset=["timestamp"], inplace=True)
data["timestamp"] = pd.to_datetime(data["timestamp"])
data.dropna(subset=["timestamp"], inplace=True)
except Exception as e:
logger.exception(f"There is an issue with the timestamp column: {e}")
raise KeyError(f"An error has occurred with the 'timestamp' column: {e}")
try:
data.dropna(subset=["timestamp"], inplace=True)
data["timestamp"] = pd.to_datetime(data["timestamp"])
except Exception as e:
logger.exception(f"There is an issue with the timestamp column: {e}")
raise KeyError(f"An error has occurred with the 'timestamp' column: {e}") from e
🧰 Tools
🪛 Ruff (0.8.2)

525-525: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

@Baalmart Baalmart merged commit 8ea5bb0 into airqo-platform:staging Jan 27, 2025
46 checks passed
@Baalmart Baalmart mentioned this pull request Jan 27, 2025
1 task
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.

2 participants