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 #4184

Merged

Conversation

NicholasTurner23
Copy link
Contributor

@NicholasTurner23 NicholasTurner23 commented Jan 9, 2025

Description

This PR does the following:

  1. Update the data clean up process to use device id and timestamp
  2. Fill data based off of the site/location and devices at that site.

Related Issues

  • JIRA cards:
    • OPS-328

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling in data extraction processes
    • Refined data filtering and query generation logic
  • Chores

    • Added retry mechanisms for data extraction tasks
    • Reduced historical data processing range from 14 to 1 day
    • Enhanced logging and error reporting
  • Refactor

    • Updated data extraction methods to provide more flexible filtering options
    • Improved duplicate data handling and removal processes

Copy link
Contributor

coderabbitai bot commented Jan 9, 2025

📝 Walkthrough

Walkthrough

This pull request introduces refinements to several utility classes and workflows in the AirQo data processing pipeline. The changes focus on improving error handling, data extraction flexibility, and task retry mechanisms across multiple Python files. The modifications enhance the robustness of data processing by adding more nuanced logging, introducing optional filtering parameters, and implementing automatic retry logic for critical tasks.

Changes

File Change Summary
src/workflows/airqo_etl_utils/airnow_utils.py Modified error handling in extract_bam_data method to log instead of raise exception
src/workflows/airqo_etl_utils/airqo_utils.py Added device_network parameter to extract_data_from_bigquery, updated remove_duplicates method logic, improved docstrings
src/workflows/airqo_etl_utils/bigquery_api.py Refined compose_query method to handle "all" network condition differently
src/workflows/dags/airqo_measurements.py Added retry logic to tasks, reduced historical data extraction range from 14 to 1 day

Sequence Diagram

sequenceDiagram
    participant DAG as Airflow DAG
    participant Extractor as Data Extractor
    participant BigQuery as BigQuery API
    participant Cleaner as Data Cleaner

    DAG->>Extractor: Extract Data
    Extractor->>BigQuery: Query with Optional Filters
    BigQuery-->>Extractor: Return Data
    Extractor->>Cleaner: Remove Duplicates
    Cleaner-->>Extractor: Cleaned Data
    Extractor->>DAG: Return Processed Data
Loading

Possibly Related PRs

Suggested Labels

ready for review

Suggested Reviewers

  • Mnoble-19
  • BenjaminSsempala
  • Baalmart
  • Psalmz777

Poem

🌍 Data flows like rivers wild,
Retry and filter, logic styled
Logs replace the loud exception's cry
Transforming code with wisdom's sigh
AirQo's pipeline, now refined and bright! 🚀

Finishing Touches

  • 📝 Generate Docstrings

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

🧹 Nitpick comments (3)
src/workflows/airqo_etl_utils/airnow_utils.py (1)

105-105: Consider using warning level logging for missing BAM data.

While changing from raising an exception to logging is good for handling expected cases, using logger.warning() instead of logger.info() would better indicate that missing BAM data might need attention, especially if data is expected for the specified date range.

-            logger.info("No BAM data found for the specified date range.")
+            logger.warning("No BAM data found for the specified date range.")
src/workflows/airqo_etl_utils/airqo_utils.py (2)

127-161: Consider using a set for better readability.

The list of non-essential columns could be more concisely defined using a set.

-        non_essential_cols = [
-            col
-            for col in data.columns
-            if col not in ["timestamp", "device_id", "device_number", "site_id"]
-        ]
+        essential_cols = {"timestamp", "device_id", "device_number", "site_id"}
+        non_essential_cols = [col for col in data.columns if col not in essential_cols]

163-174: Consider adding progress logging for large datasets.

When processing large datasets, it would be helpful to log progress during the group-by operations.

         filled_duplicates = []
+        total_groups = len(duplicates.groupby("site_id"))
+        processed_groups = 0
         for _, group in duplicates.groupby("site_id"):
+            processed_groups += 1
+            if processed_groups % 100 == 0:  # Log every 100 groups
+                logger.info(f"Processing duplicates: {processed_groups}/{total_groups} groups completed")
             group = group.sort_values(by=["device_id", "timestamp"])
             group[columns_to_fill] = (
                 group[columns_to_fill].fillna(method="ffill").fillna(method="bfill")
             )
             group = group.drop_duplicates(
                 subset=["device_id", "timestamp"], keep="first"
             )
             filled_duplicates.append(group)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 263b81e and de3af42.

📒 Files selected for processing (4)
  • src/workflows/airqo_etl_utils/airnow_utils.py (1 hunks)
  • src/workflows/airqo_etl_utils/airqo_utils.py (1 hunks)
  • src/workflows/airqo_etl_utils/bigquery_api.py (1 hunks)
  • src/workflows/dags/airqo_measurements.py (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (6)
src/workflows/dags/airqo_measurements.py (2)

218-224: LGTM! Improved error handling with retry logic and optimized timeframe.

The changes enhance robustness and efficiency:

  1. Added retry mechanism (3 retries with 5-minute delays) helps handle transient failures
  2. Reduced timeframe from 14 to 1 day optimizes processing load

Also applies to: 232-238


Line range hint 258-274: Verify the retry configuration across tasks.

The retry configuration (3 retries, 5-minute delays) has been consistently applied to data extraction and loading tasks. However, let's verify if similar retry logic should be applied to other tasks in the DAG for consistency.

✅ Verification successful

Retry configuration is appropriately implemented based on task responsibilities

The retry configuration has been correctly applied to tasks that interact with external services (data extraction, API calls, database operations), while pure computational tasks appropriately omit retry logic. This pattern is consistent and follows best practices for task resilience.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for @task decorators without retry configuration
rg "@task\(" --type py | grep -v "retries="

Length of output: 10968


Script:

#!/bin/bash
# Search for task implementations in airqo_measurements.py that use external services
rg -A 5 "@task" src/workflows/dags/airqo_measurements.py

Length of output: 9395

src/workflows/airqo_etl_utils/bigquery_api.py (1)

570-571: LGTM! Improved network filtering logic.

The explicit check for network != "all" provides clearer control over network filtering in SQL queries. This change aligns well with the network-based filtering enhancements across the codebase.

src/workflows/airqo_etl_utils/airqo_utils.py (3)

69-89: LGTM! Well-documented method signature with clear type hints.

The addition of the optional device_network parameter and comprehensive docstring improves code clarity and maintainability.


92-96: LGTM! Improved table selection logic.

Using a dictionary for table mapping is more maintainable and less error-prone than conditional statements.


108-124: LGTM! Comprehensive docstring for remove_duplicates method.

The detailed docstring clearly explains the method's purpose, steps, and expectations.

@Baalmart Baalmart merged commit 41ff27e into airqo-platform:staging Jan 9, 2025
46 checks passed
@Baalmart Baalmart mentioned this pull request Jan 9, 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