feat: add database seed script for sample satellite data#50
Conversation
|
CodeAnt AI is reviewing your PR. |
📝 WalkthroughWalkthroughA standalone Python script now seeds MongoDB with sample organizations, satellites, orbital elements, telemetry, debris, and conjunction predictions. It includes orbital-data helpers, CLI options, README instructions, and pytest coverage using in-memory database and session fakes. ChangesDatabase seeding
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Developer
participant seed_database
participant MongoDB
participant SessionLocal
Developer->>seed_database: run with count and clear options
seed_database->>MongoDB: connect and optionally clear collections
seed_database->>SessionLocal: create and commit relational records
seed_database->>MongoDB: insert orbital, telemetry, and conjunction documents
seed_database-->>Developer: print seeding summary
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
|
CodeAnt AI finished reviewing your PR. |
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (1)
backend/tests/test_seed.py (1)
99-105: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winVerify the checksum value, not only its character type.
The current assertions pass for any trailing digit, so an incorrect checksum algorithm remains undetected. Independently recompute the checksum over the first 68 characters and compare it with the final digit.
🤖 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_seed.py` around lines 99 - 105, Update the checksum assertions in the seed test to independently recompute the checksum from the first 68 characters of each line and compare the calculated value with the final digit, replacing the current isdigit-only checks while preserving the length assertions.
🤖 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/scripts/seed_db.py`:
- Around line 122-136: The --clear flow currently deletes organization data
despite documenting a non-organization scope. In backend/scripts/seed_db.py
lines 122-136, remove "organizations" from collections_to_clear; update
backend/scripts/seed_db.py lines 415-419 to list the exact collections cleared;
and update README.md lines 293-295 to document the same scope using “deletes”
rather than “drops.”
- Around line 167-184: The used_norad_ids set currently tracks only IDs
generated in the current run. In backend/scripts/seed_db.py lines 167-184,
initialize it with NORAD IDs from existing space-object records before
generating satellites, while preserving generated-ID checks. In
backend/scripts/seed_db.py lines 287-291, reuse this combined
persisted-and-generated used_norad_ids set when generating debris.
- Around line 68-76: Use one consistent COSPAR designator for each seeded record
and its TLE. In generate_tle, accept the designator as an argument instead of
generating it internally; in the launch-data flow around lines 193-205, derive
one designator, pass it to generate_tle, and store that same value as cospar_id;
in the debris flow around lines 300-307, persist the generated designator or
leave the TLE designator blank when cospar_id is None.
- Around line 109-120: Extend the try block in seed_database to cover the entire
seeding workflow, including deletes, queries, inserts, and commits. Add a
finally block that always closes db, and have the except block report the
failure without calling sys.exit; let main() handle the exit code while
preserving successful completion behavior.
- Around line 422-425: Update the count validation in the seed script’s
argument-handling flow to reject values exceeding the 40,000 available NORAD
IDs, preventing the uniqueness loop from exhausting its finite range. Keep the
existing positive-count validation, and use the available-capacity limit before
satellite ID generation; alternatively, change generation to sample IDs without
replacement so valid counts cannot loop indefinitely.
- Around line 358-368: The risk classification in the seed generation logic
makes LOW conjunctions effectively unreachable because prob is sampled from a
range above the MEDIUM threshold. Update the probability range or boundary
conditions used by the risk-level branches so LOW is generated for valid
low-risk combinations, while preserving the existing CRITICAL, HIGH, and MEDIUM
ordering and thresholds.
In `@backend/tests/test_seed.py`:
- Around line 108-119: Update test_seed_database around the mocked
get_mongo_client setup to configure fake_db.client.__getitem__ to return
fake_db, then pre-populate sentinel records in fake_db.collections before
calling seed_database(count=10, clear=True). Keep the existing mocked session
and seeding flow so the test verifies that clear removes those records as well
as validating insertion.
- Around line 131-133: Update the telemetry assertion in the seed test to derive
the expected count from the generated satellite statuses, rather than asserting
telemetry documents are greater than zero. Ensure the assertion remains valid
when all satellites are randomly inactive and verifies telemetry is created only
for active or degraded satellites.
---
Nitpick comments:
In `@backend/tests/test_seed.py`:
- Around line 99-105: Update the checksum assertions in the seed test to
independently recompute the checksum from the first 68 characters of each line
and compare the calculated value with the final digit, replacing the current
isdigit-only checks while preserving the length assertions.
🪄 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: fa89ebc7-55dd-46b1-822e-c733c658061c
📒 Files selected for processing (3)
README.mdbackend/scripts/seed_db.pybackend/tests/test_seed.py
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 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/scripts/seed_db.py`:
- Around line 204-207: Update the satellite and debris call sites that invoke
generate_tle to pass the already calculated epoch value, and revise generate_tle
to accept and use that epoch instead of independently randomizing one. Ensure
each generated TLE’s epoch matches the persisted orbital epoch.
- Around line 228-262: Update the space-object creation flow around the
`space_obj` and `Satellite`/`Debris` records so each parent-child pair is
persisted in a single transaction, removing the intermediate `db.commit()`
before constructing the linked record. Add both objects to the session, commit
once, refresh them afterward as needed, and ensure a failed child insert rolls
back the transaction without leaving an orphaned `SpaceObject`.
- Around line 281-285: Update the battery_charge assignment in the telemetry
generation block to use an independent random battery reading rather than
sat.fuel_percentage, while preserving the existing 0–100 clamping and the other
telemetry fields.
- Around line 168-180: Update the pre-loading error handling in the seed flow
around the existing satellites/debris queries to abort immediately when
persisted NORAD IDs cannot be loaded. Do not continue seeding after the
exception; report the failure and propagate or explicitly terminate through the
script’s established failure path before any writes occur.
🪄 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: 34814ace-6446-428c-929c-8dd399f489a4
📒 Files selected for processing (2)
backend/scripts/seed_db.pybackend/tests/test_seed.py
🚧 Files skipped from review as they are similar to previous changes (1)
- backend/tests/test_seed.py
|
i solve this issue can check and merge it |
User description
Description
Created a standalone database seed script (
seed_db.py) to generate realistic and randomized satellite, space debris, telemetry logs, and conjunction predictions in MongoDB. Added comprehensive unit tests and documented setup instructions in the README.Related Issue
Fixes #31
Checklist
Screenshots / Screen Recordings
(N/A)
Breaking Changes
None
ECSoC26 Submission
ECSoC26-L1– BeginnerECSoC26-L2– IntermediateECSoC26-L3– AdvancedCodeAnt-AI Description
Add a database seed script for realistic satellite sample data
What Changed
Impact
✅ Faster local setup✅ Easier demo data generation✅ Fewer manual test records💡 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
New Features
MONGODB_URI.Documentation
Tests
Greptile Summary
This PR adds a standalone database seed script (
backend/scripts/seed_db.py) that populates MongoDB with sample organizations, satellites, space debris, telemetry logs, and conjunction predictions for local development. It also adds unit tests and a README section documenting CLI options and environment variable configuration.calculate_semimajor_axis,generate_tle, a full seeded run, and a no-clear incremental run — but the no-clear test'smongo_dbis a disconnectedMagicMock, so the NORAD deduplication path it is supposed to exercise is never reached.satellite_id=str(sat.id)stores a string FK in telemetry while the ORM layer indexes by integerid, causing everytelemetry→satelliterelationship lookup to silently returnNone.Confidence Score: 3/5
Not ready to merge — the telemetry satellite foreign key is stored as a string while the ORM resolves it as an integer, silently breaking every telemetry relationship lookup.
The satellite_id type mismatch is still present in the diff and silently breaks every telemetry-to-satellite relationship lookup produced by this script. Combined with the --clear user orphaning issue also still present, this script needs another pass before the seeded data is reliable.
backend/scripts/seed_db.py — the telemetry seeding block at line 226 still stores satellite_id as str(sat.id); this needs to be corrected to sat.id (integer) before the script produces usable linked data.
Important Files Changed
Flowchart
%%{init: {'theme': 'neutral'}}%% flowchart TD A[seed_database called] --> B{--clear flag?} B -- Yes --> C[Drop satellites, debris, orbitalElements,\ntelemetry, conjunctions, organizations\n+ reset counters] B -- No --> D[Pre-load existing NORAD IDs\nfrom satellites + debris collections] C --> E[Seed 5 Organizations\ncheck for existing by name] D --> E E --> F[Generate N Satellites\nSpaceObject + Satellite per record\nunique NORAD ID 10000-49999] F --> G[Seed Telemetry\n5 points per ACTIVE/DEGRADED satellite] G --> H[Generate N/2 Debris\nSpaceObject + Debris per record\nunique NORAD ID 50000-89999] H --> I[Seed Conjunctions\nmin-5 satellite-debris pairs\nrisk level based on miss_distance + prob] I --> J[db.commit + db.close] J --> K[Print summary]%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%% flowchart TD A[seed_database called] --> B{--clear flag?} B -- Yes --> C[Drop satellites, debris, orbitalElements,\ntelemetry, conjunctions, organizations\n+ reset counters] B -- No --> D[Pre-load existing NORAD IDs\nfrom satellites + debris collections] C --> E[Seed 5 Organizations\ncheck for existing by name] D --> E E --> F[Generate N Satellites\nSpaceObject + Satellite per record\nunique NORAD ID 10000-49999] F --> G[Seed Telemetry\n5 points per ACTIVE/DEGRADED satellite] G --> H[Generate N/2 Debris\nSpaceObject + Debris per record\nunique NORAD ID 50000-89999] H --> I[Seed Conjunctions\nmin-5 satellite-debris pairs\nrisk level based on miss_distance + prob] I --> J[db.commit + db.close] J --> K[Print summary]Reviews (3): Last reviewed commit: "test: apply CodeRabbit suggestion for ex..." | Re-trigger Greptile