Skip to content

feat(brain): implement APScheduler for background market syncing and scanning#15

Merged
Harikeshav-R merged 2 commits into
mainfrom
feat/brain/task-scheduler
Feb 28, 2026
Merged

feat(brain): implement APScheduler for background market syncing and scanning#15
Harikeshav-R merged 2 commits into
mainfrom
feat/brain/task-scheduler

Conversation

@Harikeshav-R

Copy link
Copy Markdown
Owner

Description

This PR introduces an in-process background task scheduler to the Python Brain service using apscheduler. Previously, market syncing and pair scanning against the Gamma API were only available via manual/external API triggers.
This change allows the Brain to become an autonomous entity that automatically runs _internal_sync_markets and _internal_scan_markets on a 15-minute interval. This is handled gracefully within the FastAPI llifespan without needing external cron jobs, heavy distributed message queues (like Celery), or blocking the main HTTP event loop.
Additionally, a bug regarding AsyncSession instantiation during Pytest execution has been resolved, allowing the get_session() generator to be properly accessed by background tasks and fixtures.

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)
  • This change requires a documentation update

How Has This Been Tested?

I ran the full pytest regression suite to ensure the refactored FastAPI /markets/sync and /scan routes still behave identically when accessed via HTTP, and that the database session lifecycle properly opens and closes during background execution.

  • Unit Tests
  • Integration Tests

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

… automation

- Added `apscheduler` integration to enable automated background tasks within the Brain service.
- Implemented a scheduler that periodically:
  - **Syncs markets** from the Gamma API every 15 minutes.
  - **Scans market pairs** for analysis using pre-defined logic.
- Refactored market sync (`_internal_sync_markets`) and scan logic (`_internal_scan_markets`) into reusable functions for both API endpoints and background jobs.
- Enhanced error handling and logging:
  - Added structured logs for sync and scan tasks via API and background jobs.
  - Improved exception handling to retain service stability.
- Introduced shutdown hooks for graceful cleanup of the scheduler during service exit.
- Updated dependencies:
  - Included `apscheduler>=3.11.2` in `pyproject.toml` and `uv.lock`.
- Added `auto_discover_and_analyze` method for integrated sync and scan in the background.

This update automates critical market update and analysis workflows, reducing manual overhead and improving operational efficiency.
Copilot AI review requested due to automatic review settings February 28, 2026 02:28

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Adds an in-process background scheduler to the Brain FastAPI service so it can periodically sync markets from Gamma and scan/analyze market pairs without external triggers.

Changes:

  • Added apscheduler dependency (and lockfile updates) for scheduled background execution.
  • Introduced an AsyncIOScheduler started/stopped from the FastAPI lifespan, running a 15-minute sync+scan job.
  • Refactored /markets/sync and /scan to delegate to internal functions so both API routes and background jobs can reuse the same logic.

Reviewed changes

Copilot reviewed 2 out of 3 changed files in this pull request and generated 7 comments.

File Description
services/brain/uv.lock Locks apscheduler and its dependency tzlocal.
services/brain/pyproject.toml Adds apscheduler to Brain service dependencies.
services/brain/main.py Adds scheduler lifecycle + background job; refactors sync/scan logic for internal reuse.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread services/brain/main.py Outdated
Comment thread services/brain/main.py Outdated
Comment thread services/brain/main.py Outdated
Comment thread services/brain/main.py
Comment thread services/brain/main.py
Comment thread services/brain/main.py Outdated
Comment thread services/brain/main.py
… analysis response messaging

- Enhanced `auto_discover_job` scheduler:
  - Added `max_instances=1` to prevent overlapping job executions.
  - Enabled `coalesce` to merge missed runs during downtime.
  - Set `misfire_grace_time=300` to allow a 5-minute buffer for delayed jobs.
- Improved error handling for API endpoints:
  - Updated generic exceptions to return a standardized "Internal server error" message for better consistency and user experience.
  - Explicitly re-raised `HTTPException` without modification.
- Refined response structure for market analysis:
  - Added more descriptive messages for scenarios with insufficient markets or analyzed pairs.
  - Included `skipped` field to clarify skipped market counts in analysis results.

These updates improve scheduler reliability, API robustness, and response clarity in the Brain service.
@Harikeshav-R Harikeshav-R merged commit 4e11f1a into main Feb 28, 2026
4 checks passed
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