fix(ingestion): persist debris records and repair the model schema (fixes #117)#118
fix(ingestion): persist debris records and repair the model schema (fixes #117)#118Amayyas wants to merge 1 commit into
Conversation
Three defects introduced by the MongoDB -> PostgreSQL migration. Each is a one-line cause with an outsized effect. 1. Debris ingestion persisted nothing at all. _gp_to_doc emits one satellite-shaped dict for every provider, but `debris` is a narrower table (no objectType/countryCode/launchDate/updatedAt/status/ fuel_percentage/operational_mode). Passing those keys through made every debris write fail — CompileError "Unconsumed column names" on PostgreSQL, TypeError on SQLite — so the catalog gained no debris on either backend. Each doc is now projected onto the target model's real columns. 2. `updatedAt` was written as an ISO string into DateTime(timezone=True). A MongoDB-era leftover: Mongo stored ISO strings, PostgreSQL does not. SQLAlchemy's SQLite DateTime rejects strings outright, so satellite ingestion failed there too. Now a real timezone-aware datetime, which also drops the deprecated utcnow(). 3. spaceWeather.recorded_at was indexed twice. Declared explicitly in __table_args__ as `ix_spaceweather_recorded_at` and again implicitly via index=True, which SQLAlchemy names `ix_spaceWeather_recorded_at`. The names differ only by case: SQLite treats identifiers case-insensitively, so create_all() died with "index already exists" and took 10 tests down at setup; PostgreSQL quotes the mixed-case name and silently creates two redundant indexes on the same column. Test suite: 40 passed + 10 errors -> 55 passed. The 5 new tests fail without these fixes, so they pin the regressions rather than merely describing them: tests/test_models_schema.py guards the metadata invariants (unique index names, no duplicate indexes, create_all works on a clean database), and two ingestion tests cover debris persistence and the timestamp type. Verified end to end against live CelesTrak data: 25 real COSMOS 1408 debris records now land in the debris table (previously 0), satellites ingest with a proper datetime, and a re-sync stays idempotent.
🤖 CodeAnt AI — Review Status
Updated in place by CodeAnt AI · last 5 reviews |
📝 WalkthroughWalkthroughThe PR fixes Space-Track debris upserts, stores satellite timestamps as timezone-aware datetimes, removes a duplicate SpaceWeather index, and adds ingestion and schema regression tests. ChangesIngestion and schema fixes
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant SpaceTrackService
participant _gp_to_doc
participant _bulk_upsert
participant Satellite
participant Debris
SpaceTrackService->>_gp_to_doc: build document with UTC datetime
SpaceTrackService->>_bulk_upsert: submit document and target model
_bulk_upsert->>Satellite: persist satellite columns
_bulk_upsert->>Debris: persist debris columns
Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@backend/tests/test_models_schema.py`:
- Around line 13-15: Update Backend CI’s pytest configuration to run from the
backend package context or include backend on PYTHONPATH, so
test_models_schema.py can resolve database and related imports during
collection. Preserve the existing pytest tests/ target and ensure the schema
regression tests execute successfully in CI.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 7603fddb-a7dd-4400-b658-b6b44a163dd5
📒 Files selected for processing (4)
backend/models/db_models.pybackend/orbital/spacetrack.pybackend/tests/test_ingestion.pybackend/tests/test_models_schema.py
| from database.session import Base | ||
| import models.db_models # noqa: F401 — registers all tables | ||
| import orbital.providers.cache # noqa: F401 — registers ProviderCache |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Make the schema test importable by Backend CI.
The configured pytest tests/ command fails during collection at Line 13 with ModuleNotFoundError: No module named 'database', producing six errors. Run tests from backend/ or configure the CI Python path to include backend so these regressions execute.
🧰 Tools
🪛 GitHub Actions: Backend CI / 0_test.txt
[error] 13-13: Pytest collection failed: ModuleNotFoundError: No module named 'database' when executing 'from database.session import Base'.
🪛 GitHub Actions: Backend CI / test
[error] 13-13: pytest collection failed due to import error: ModuleNotFoundError: No module named 'database' (from 'from database.session import Base').
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@backend/tests/test_models_schema.py` around lines 13 - 15, Update Backend
CI’s pytest configuration to run from the backend package context or include
backend on PYTHONPATH, so test_models_schema.py can resolve database and related
imports during collection. Preserve the existing pytest tests/ target and ensure
the schema regression tests execute successfully in CI.
Source: Pipeline failures
|
@Amayyas Thanks for your contribution!!
Due to the mock data, we can't merge this PR right now. |

User description
Description
Fixes three defects introduced by the MongoDB → PostgreSQL migration. Each has a one-line cause but an outsized effect — the first means Kepler currently ingests no debris at all, on either backend.
I found these while checking that the multi-source provider work (#15) still ran after the migration: the backend test suite does not pass on
maintoday.1. Debris ingestion persisted nothing 🔴
_gp_to_docemits one satellite-shaped dict for every provider, butdebrisis a narrower table — noobjectType,countryCode,launchDate,updatedAt,status,fuel_percentage,operational_mode. Passing those keys through made every debris write fail:On PostgreSQL the whole batch is rolled back and marked failed; on SQLite it fails row by row. Either way the debris catalog stayed empty — on a platform built for debris collision avoidance.
Fix: project each document onto the target model's real columns at the write boundary, which covers both dialects and both models.
2.
updatedAtwritten as a string into aDateTimecolumn 🟠now = datetime.datetime.utcnow().isoformat()produced a string for aDateTime(timezone=True)column — a MongoDB-era leftover (Mongo stored ISO strings, PostgreSQL does not). SQLAlchemy's SQLiteDateTimerejects strings outright, so satellite ingestion failed there too.Fix: a real timezone-aware
datetime, which also drops the deprecatedutcnow().3.
spaceWeather.recorded_atindexed twice 🟠Declared explicitly in
__table_args__and implicitly viaindex=True. The generated names differ only by case:create_all()aborts with "index already exists", taking 10 tests down at fixture setup.Fix: drop the redundant
index=True, keeping the explicitly-named index that matches the convention used by the other tables (ix_satellites_noradid,ix_alerts_created_at, …).Related Issue
Fixes #117
Checklist
Testing
The 5 new tests fail without these fixes, so they pin the regressions rather than merely describing them (verified by stashing the fixes and re-running):
tests/test_models_schema.py— schema invariants: index names unique case-insensitively, no duplicate indexes on the same columns, andcreate_all()succeeds on a clean database. These guard the metadata itself, so a bad declaration fails at collection time instead of surfacing as a confusing error in an unrelated test.tests/test_ingestion.py— debris records are persisted, andupdatedAtround-trips as adatetimerather than a string.Verified end to end against live CelesTrak data, not just via tests: 25 real
COSMOS 1408 DEBrecords now land in thedebristable (previously 0), satellites ingest with a properdatetime, and a re-sync stays idempotent (no duplicates).Breaking Changes
None. No API contract or schema shape changes — the removed index was a duplicate of one that remains, so PostgreSQL deployments simply stop maintaining a second copy. Existing databases need no migration.
CodeAnt-AI Description
Fix debris ingestion, timestamp storage, and schema setup failures
What Changed
updatedAtas a real date and time value, which avoids ingestion failures from text timestampsImpact
✅ Debris objects now appear in the catalog✅ Fewer ingestion failures on fresh databases✅ Safer schema setup during test runs💡 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:
This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.
Example
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:
This helps CodeAnt AI learn and adapt to your team's coding style and standards.
Example
Retrigger review
Ask CodeAnt AI to review the PR again, by typing:
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.
Summary by CodeRabbit
Bug Fixes
Tests
Greptile Summary
This PR repairs debris ingestion and removes a duplicate schema index. The main changes are:
Confidence Score: 5/5
This looks safe to merge.
Important Files Changed
Reviews (1): Last reviewed commit: "fix(ingestion): persist debris records a..." | Re-trigger Greptile