Skip to content

feat: add database seed script for sample satellite data#50

Merged
krishkhinchi merged 3 commits into
7-Blocks:mainfrom
nayanraj864-cmyk:feat/add-database-seed-script
Jul 16, 2026
Merged

feat: add database seed script for sample satellite data#50
krishkhinchi merged 3 commits into
7-Blocks:mainfrom
nayanraj864-cmyk:feat/add-database-seed-script

Conversation

@nayanraj864-cmyk

@nayanraj864-cmyk nayanraj864-cmyk commented Jul 16, 2026

Copy link
Copy Markdown

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

  • I have read the contributing guidelines
  • My code follows the project guidelines
  • I have completed testing of my changes
  • Documentation has been updated (if applicable)

Screenshots / Screen Recordings

(N/A)

Breaking Changes

None


ECSoC26 Submission

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

CodeAnt-AI Description

Add a database seed script for realistic satellite sample data

What Changed

  • Added a script to populate MongoDB with sample organizations, satellites, space debris, telemetry, and collision alerts for local development and demos
  • Added options to control how many satellites are created and to clear existing seeded records before running
  • Added tests for the orbit math, TLE generation, and a full seed run
  • Documented how to run the seeding script and configure the database connection

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:

@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.

Summary by CodeRabbit

  • New Features

    • Added a database seeding tool that populates local MongoDB with sample satellites, telemetry, debris, and collision predictions.
    • Added options to control the number of records and clear existing data before seeding.
    • Added support for configuring the MongoDB connection through MONGODB_URI.
  • Documentation

    • Added Getting Started instructions covering database seeding and available command options.
  • Tests

    • Added automated coverage for generated orbital data, TLE records, and seeded database contents.

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.

  • Seed script: creates SpaceObject + model records for each satellite and debris item, seeds telemetry for active/degraded satellites, and generates up to 5 conjunction events with risk classification.
  • Tests: cover calculate_semimajor_axis, generate_tle, a full seeded run, and a no-clear incremental run — but the no-clear test's mongo_db is a disconnected MagicMock, so the NORAD deduplication path it is supposed to exercise is never reached.
  • Unfixed from prior review: satellite_id=str(sat.id) stores a string FK in telemetry while the ORM layer indexes by integer id, causing every telemetry→satellite relationship lookup to silently return None.

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

Filename Overview
backend/scripts/seed_db.py Seed script with logic bugs: satellite_id stored as string (unfixed from previous review), risk_level "LOW" dead code, and partially-effective NORAD deduplication.
backend/tests/test_seed.py Tests have a structural gap: mongo_db used for pre-loading existing NORAD IDs is a disconnected MagicMock, not FakeDb, so test_seed_database_no_clear doesn't actually validate deduplication.
README.md Adds a "Database Seeding" section with clear usage instructions, CLI options, and environment variable documentation.

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]
Loading
%%{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]
Loading

Reviews (3): Last reviewed commit: "test: apply CodeRabbit suggestion for ex..." | Re-trigger Greptile

@codeant-ai

codeant-ai Bot commented Jul 16, 2026

Copy link
Copy Markdown

CodeAnt AI is reviewing your PR.

@github-actions github-actions Bot added backend Backend development bug Something isn't working database Database and schema related changes documentation Improvements or additions to documentation size/XL Very large or complex contribution. testing Tests added or improved type:backend Changes backend services or server-side logic. type:bug Fixes an existing bug or unexpected behavior. type:documentation Improves project documentation. type:testing Adds or updates automated tests. labels Jul 16, 2026
@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

A 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.

Changes

Database seeding

Layer / File(s) Summary
Orbital data generation
backend/scripts/seed_db.py, backend/tests/test_seed.py
Sample datasets, semi-major-axis calculations, checksum-valid TLE generation, and unit tests for these utilities are added.
Database population
backend/scripts/seed_db.py, backend/tests/test_seed.py
The seeding routine clears selected collections when requested and creates organizations, satellites, telemetry, debris, orbital elements, and conjunction predictions using mocked integration tests.
CLI and usage documentation
backend/scripts/seed_db.py, README.md
The script exposes configurable count and clear flags, validates positive counts, and documents execution plus MongoDB URI configuration.

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
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.04% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR adds a configurable MongoDB seed script, realistic sample data, console output, and documentation as required by #31.
Out of Scope Changes check ✅ Passed The changes stay focused on seeding, tests, and documentation, with no clear unrelated additions.
Title check ✅ Passed The title clearly summarizes the main change: adding a database seed script for sample satellite data.
Description check ✅ Passed The description matches the template well and includes all required sections, including issue, checklist, screenshots, breaking changes, and ECSoC26 selection.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@codeant-ai codeant-ai Bot added the size:XL This PR changes 500-999 lines, ignoring generated files label Jul 16, 2026
@github-actions github-actions Bot added AI Artificial Intelligence and Machine Learning enhancement New feature or request type:feature Introduces a new feature or enhancement. labels Jul 16, 2026
Comment thread backend/scripts/seed_db.py Outdated
Comment thread backend/scripts/seed_db.py Outdated
Comment thread backend/scripts/seed_db.py
Comment thread backend/tests/test_seed.py Outdated
@codeant-ai

codeant-ai Bot commented Jul 16, 2026

Copy link
Copy Markdown

CodeAnt AI finished reviewing your PR.

Comment thread backend/scripts/seed_db.py Outdated
Comment thread backend/scripts/seed_db.py Outdated
Comment thread backend/scripts/seed_db.py
Comment thread backend/scripts/seed_db.py Outdated
Comment thread backend/tests/test_seed.py

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 8

🧹 Nitpick comments (1)
backend/tests/test_seed.py (1)

99-105: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Verify 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

📥 Commits

Reviewing files that changed from the base of the PR and between e98f65b and c076b64.

📒 Files selected for processing (3)
  • README.md
  • backend/scripts/seed_db.py
  • backend/tests/test_seed.py

Comment thread backend/scripts/seed_db.py
Comment thread backend/scripts/seed_db.py Outdated
Comment thread backend/scripts/seed_db.py Outdated
Comment thread backend/scripts/seed_db.py Outdated
Comment thread backend/scripts/seed_db.py Outdated
Comment thread backend/scripts/seed_db.py
Comment thread backend/tests/test_seed.py
Comment thread backend/tests/test_seed.py Outdated
@github-actions github-actions Bot added ECSoC26 Official label for ECSoC26 event contributions. ECSoC26-L2 Level 2 contribution for the ECSoC26 event. labels Jul 16, 2026

@coderabbitai coderabbitai Bot 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between c076b64 and 7644544.

📒 Files selected for processing (2)
  • backend/scripts/seed_db.py
  • backend/tests/test_seed.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/tests/test_seed.py

Comment thread backend/scripts/seed_db.py
Comment thread backend/scripts/seed_db.py
Comment thread backend/scripts/seed_db.py
Comment thread backend/scripts/seed_db.py
@nayanraj864-cmyk

Copy link
Copy Markdown
Author

i solve this issue can check and merge it

@krishkhinchi
krishkhinchi merged commit 4d5f601 into 7-Blocks:main Jul 16, 2026
8 of 10 checks passed
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-L2 Level 2 contribution for the ECSoC26 event. ECSoC26 Official label for ECSoC26 event contributions. enhancement New feature or request size/XL Very large or complex contribution. size:XL This PR changes 500-999 lines, ignoring generated files testing Tests added or improved 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. type:testing Adds or updates automated tests.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add Database Seed Script for Sample Satellite Data

2 participants