Skip to content

fix(backend): resolve memory leak and db pagination in catalog API - #195

Merged
krishkhinchi merged 1 commit into
7-Blocks:mainfrom
AryanYadav215:fix/capi-catalog-pagination
Aug 15, 2026
Merged

fix(backend): resolve memory leak and db pagination in catalog API#195
krishkhinchi merged 1 commit into
7-Blocks:mainfrom
AryanYadav215:fix/capi-catalog-pagination

Conversation

@AryanYadav215

@AryanYadav215 AryanYadav215 commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

User description

Summary

This PR addresses severe performance and logic bugs in the CAPI backend related to database schema queries. The /api/v1/catalog/objects endpoint previously queried Satellite and Debris separately, loading the entire database table into memory (.all()) before manually slicing the array in Python. It also had a syntax bug calculating the total pages (pages = (total + size - 1) missing the // size operator).

This update refactors the endpoint to query the unified SpaceObject schema, enabling .offset() and .limit() pagination at the database level, preventing memory exhaustion and fixing the pagination metadata.

Related Issue

Closes #193

Type of Change

  • 🐛 Bug fix
  • ✨ New feature
  • 📝 Documentation update
  • 🚀 Performance improvement
  • 🎨 UI/UX enhancement
  • ♻️ Refactoring
  • 🧹 Chore / Maintenance
  • 🔒 Security improvement

Screenshots / Screen Recordings

No essential SS required

Testing Performed

  • Tested locally
  • Tested relevant functionality (Verified the /objects endpoint correctly paginates and filters by classification)
  • Checked for linting errors
  • Checked for TypeScript/build errors
  • Tested responsive behavior (if applicable)

Breaking Changes

None. The API response schema remains perfectly intact.

Checklist

  • I have read and followed the contributing guidelines.
  • My code follows the project's coding standards and guidelines.
  • I have completed testing of my changes.
  • I have updated documentation where applicable.
  • I have checked that my changes do not introduce unintended regressions.

ECSoC26 Submission

  • ECSoC26-L1 – Beginner
  • ECSoC26-L2 – Intermediate
  • ECSoC26-L3 – Advanced

CodeAnt-AI Description

Fix catalog pagination and reduce memory use for large object lists

What Changed

  • Catalog results are filtered and paginated in the database instead of loading the full catalog into memory
  • Pagination totals and page counts now reflect the requested page size correctly
  • Catalog responses continue to include object details such as classification, orbital data, TLE availability, and update time

Impact

✅ Lower memory use for large catalog requests
✅ Correct page counts and result totals
✅ Faster catalog responses for paginated queries

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Refactored the /objects endpoint to query the SpaceObject schema directly, enabling SQL-level pagination and resolving the missing integer division bug in page calculations.
@codeant-ai

codeant-ai Bot commented Aug 14, 2026

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Reviewed your PR ad479cd Aug 14, 2026 · 21:52 21:55

@codeant-ai

codeant-ai Bot commented Aug 14, 2026

Copy link
Copy Markdown

Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@github-actions github-actions Bot added ECSoC26 Official label for ECSoC26 event contributions. ECSoC26-L2 Level 2 contribution for the ECSoC26 event. backend Backend development bug Something isn't working database Database and schema related changes documentation Improvements or additions to documentation enhancement New feature or request size/M Medium-sized contribution. size:M This PR changes 30-99 lines, ignoring generated files type:backend Changes backend services or server-side logic. type:bug Fixes an existing bug or unexpected behavior. type:documentation Improves project documentation. type:feature Introduces a new feature or enhancement. labels Aug 14, 2026
@coderabbitai

coderabbitai Bot commented Aug 14, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@AryanYadav215, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 43 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 900dac25-5fff-4aa7-9eae-fd9f52f0d8b0

📥 Commits

Reviewing files that changed from the base of the PR and between 120b23b and ad479cd.

📒 Files selected for processing (1)
  • backend/api/v1/endpoints/catalog.py

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

Comment @coderabbitai help to get the list of available commands.

@codeant-ai codeant-ai Bot added size:M This PR changes 30-99 lines, ignoring generated files and removed size:M This PR changes 30-99 lines, ignoring generated files labels Aug 14, 2026
@github-actions github-actions Bot added the AI Artificial Intelligence and Machine Learning label Aug 14, 2026
Comment on lines +117 to +118
@router.get("/objects", response_model=APIResponse[List[Dict[str, Any]]])
def _serialize_space_object(obj: SpaceObject) -> Dict[str, Any]:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: The serializer is incorrectly registered as a second GET /objects route. Because this route is declared before list_space_objects, requests to /api/v1/catalog/objects match _serialize_space_object first; obj is treated as a request parameter rather than a database dependency, so the listing endpoint returns validation errors or the application can fail during FastAPI route initialization. Remove the route decorator from this helper and leave only list_space_objects registered for this path. [api mismatch]

Severity Level: Critical 🚨
- ❌ Catalog application startup or `/objects` requests fail.
- ❌ Frontend catalog data cannot load from `/api/v1/catalog/objects`.
- ⚠️ Pagination and classification filters become unreachable.

Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** backend/api/v1/endpoints/catalog.py
**Line:** 117:118
**Comment:**
	*Api Mismatch: The serializer is incorrectly registered as a second GET `/objects` route. Because this route is declared before `list_space_objects`, requests to `/api/v1/catalog/objects` match `_serialize_space_object` first; `obj` is treated as a request parameter rather than a database dependency, so the listing endpoint returns validation errors or the application can fail during FastAPI route initialization. Remove the route decorator from this helper and leave only `list_space_objects` registered for this path.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Comment on lines +157 to +158
# FIX: Query the unified SpaceObject schema to enable DB-level pagination
query = db.query(SpaceObject)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: The endpoint now counts and retrieves only rows from SpaceObject, but the Space-Track synchronization code upserts records exclusively into Satellite or Debris. Newly synchronized catalog records, and existing records present only in those tables, therefore do not appear in this endpoint and are omitted from total and pagination. Either populate SpaceObject as part of synchronization or query the source tables consistently. [incomplete implementation]

Severity Level: Critical 🚨
- ❌ Synchronized satellites disappear from catalog listings.
- ❌ Synchronized debris are omitted from totals.
- ⚠️ Classification filters and pagination metadata become incomplete.

Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** backend/api/v1/endpoints/catalog.py
**Line:** 157:158
**Comment:**
	*Incomplete Implementation: The endpoint now counts and retrieves only rows from `SpaceObject`, but the Space-Track synchronization code upserts records exclusively into `Satellite` or `Debris`. Newly synchronized catalog records, and existing records present only in those tables, therefore do not appear in this endpoint and are omitted from `total` and pagination. Either populate `SpaceObject` as part of synchronization or query the source tables consistently.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Comment on lines +171 to +172
# FIX: Correct the pagination math
pages = (total + size - 1) // size

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: For an empty filtered catalog, this formula produces pages=0, while the other paginated catalog APIs return one page for an empty result set. Clients using the shared pagination contract can therefore receive an inconsistent or invalid page count when no objects match. Preserve the empty-result behavior by returning one page when total is zero. [api mismatch]

Severity Level: Major ⚠️
- ⚠️ Empty catalog filters return inconsistent page metadata.
- ⚠️ Clients may treat zero pages as invalid pagination.
- ⚠️ Catalog behavior differs from other paginated APIs.

Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** backend/api/v1/endpoints/catalog.py
**Line:** 171:172
**Comment:**
	*Api Mismatch: For an empty filtered catalog, this formula produces `pages=0`, while the other paginated catalog APIs return one page for an empty result set. Clients using the shared pagination contract can therefore receive an inconsistent or invalid page count when no objects match. Preserve the empty-result behavior by returning one page when `total` is zero.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

@krishkhinchi krishkhinchi left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM!!

@krishkhinchi
krishkhinchi merged commit 19408f5 into 7-Blocks:main Aug 15, 2026
11 of 12 checks passed
@ecsoc-sentinel ecsoc-sentinel Bot added ECSoC26-L1 Level 1 contribution for the ECSoC26 event. and removed ECSoC26-L2 Level 2 contribution for the ECSoC26 event. labels Aug 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI Artificial Intelligence and Machine Learning backend Backend development bug Something isn't working database Database and schema related changes documentation Improvements or additions to documentation ECSoC26-L1 Level 1 contribution for the ECSoC26 event. ECSoC26 Official label for ECSoC26 event contributions. enhancement New feature or request size/M Medium-sized contribution. size:M This PR changes 30-99 lines, ignoring generated files type:backend Changes backend services or server-side logic. type:bug Fixes an existing bug or unexpected behavior. type:documentation Improves project documentation. type:feature Introduces a new feature or enhancement.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

## [Bug]: Unhandled Upstream Failures in Catalog Fallback Sync

2 participants