← Back to Pull requests

[AAP-103747] perf(tasks): avoid redundant JSONB serialization and reduce scheduler per-tick overhead #555

Closed
unknown closed this pull request without merging on Nov 27, 2026 10:33 UTC
View on GitHub
unknown unknown commented on Nov 26, 2026 14:36 UTC
Author

Description


  • What is being changed?

  • - apps/core/json_utils.py: adds an optional normalized: bool = False keyword argument to json_size_bytes() so callers with already-normalized data can compute byte size without running to_jsonable() a second time.
    - apps/tasks/models.py: updates HourlyMetricsCollection.save() and AnonymizedMetricsPayload.save() to pass normalized=True to json_size_bytes() and skip re-normalizing/re-sizing when update_fields is passed without the JSON data column (automatically appending data_size_bytes/payload_size_bytes when the data column is written). Also chains .defer("result_data", "error_message", "description") onto Task.immediate_tasks(), Task.scheduled_tasks(), and Task.recurring_tasks().
    - apps/tasks/collectors/send_anonymized_to_segment.py & apps/tasks/collectors/daily_anonymize_and_prepare.py: adds .select_related("daily_summary") to _get_payloads_to_send() and passes explicit update_fields (always including "modified") on status-only .save() calls.
    - apps/tasks/cron_scheduler.py: fetches only IDs via .values_list("id", flat=True) in _fail_stuck_tasks() and caches TASK_LOCKS hashtext() IDs per UnifiedTaskScheduler instance in _cleanup_stale_advisory_locks().
    - Adds unit tests covering single-pass normalization, update_fields SQL exclusion, select_related, deferred discovery queries, and per-instance lock hash caching.
  • Why is this change needed?

  • - Saving HourlyMetricsCollection / AnonymizedMetricsPayload walked large nested JSON dicts twice, and status-only updates re-normalized and rewrote full multi-MB JSONB columns on every transition. Meanwhile, the periodic scheduler fetched unused result_data blobs and re-queried static TASK_LOCKS hashes every 30 seconds.
  • How does this change address the issue?

  • - Eliminates duplicate to_jsonable() walks, restricts status-transition UPDATEs to changed scalar columns, prefetches daily_summary, defers unused Task columns on scheduler ticks, and caches lock hashes per scheduler instance. In paired benchmarks on a containerized reference deployment (RHEL 9.6, Python 3.12, Django 5.2, PostgreSQL 15, identical SHA-256 output digests):
    - JSON saves & Segment send transitions: 3.13× faster on status-transition sends (5.219s → 1.669s), 1.60× faster overall (11.202s → 7.016s), -47.7 MiB peak RSS, -10 queries
    - Scheduler ticks (50 ticks): 5.68× faster (7.947s → 1.399s), hashtext queries 50 → 1, -17.8 MiB peak RSS

    Type of Change


  • Bug fix (non-breaking change which fixes an issue)

  • New feature (non-breaking change which adds functionality)

  • Breaking change (fix or feature that would cause existing functionality to not work as expected)

  • Documentation update

  • Test update

  • Refactoring (no functional changes)

  • Development environment change

  • Configuration change
  • Self-Review Checklist


  • I have performed a self-review of my code

  • I have added relevant comments to complex code sections

  • I have updated documentation where needed

  • I have considered the security impact of these changes

  • I have considered performance implications

  • I have thought about error handling and edge cases

  • I have tested the changes in my local environment
  • Testing Instructions


    Prerequisites


  • Local PostgreSQL instance running (e.g. make compose or local test DB)
  • Steps to Test


    1. Run lint and format checks:
       uv run ruff format --check apps/ tests/
       uv run ruff check apps/ tests/
       

    2. Run the targeted test suites:
       METRICS_SERVICE_MODE=test uv run pytest \
         tests/unit/core/test_json_utils.py \
         tests/unit/tasks/test_save_serialization_efficiency.py \
         tests/unit/tasks/test_cron_scheduler.py \
         tests/coverage/tasks/test_cron_scheduler.py \
         tests/coverage/tasks/test_send_to_segment.py \
         tests/coverage/tasks/test_segment_sender_extended.py \
         tests/unit/tasks/collectors/test_daily_anonymize_and_prepare.py \
         tests/unit/tasks/test_models_enhanced.py
       

    Expected Results


  • Ruff checks pass and all 169 tests pass, verifying single-pass JSON normalization, status-only UPDATE SQL without JSONB rewrites (with modified updated), daily_summary prefetching, deferred scheduler discovery columns, and single hashtext resolution per scheduler instance.
  • Diff: 557 lines (+417 / -140) across 6 files Reviewer: redhat-chai-bot Review duration: 1196m
    All Vouch review confidence checks passed
    Residual risk 0.19 = Change Risk (0.48) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.48 · 557 lines diff across 6 files
    0.48
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.378
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #555"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 48.2% (MEDIUM) · Higher = larger blast radius
    48.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 19% · Safe to merge
    19%