Skip to content

Add harvest_input and knowledge_queue models with pipeline support#989

Open
manshusainishab wants to merge 6 commits into
OWASP:mainfrom
manshusainishab:module_b_w5
Open

Add harvest_input and knowledge_queue models with pipeline support#989
manshusainishab wants to merge 6 commits into
OWASP:mainfrom
manshusainishab:module_b_w5

Conversation

@manshusainishab

Copy link
Copy Markdown
Contributor

Summary

Wires Module B (Noise/Relevance Filter) into the orchestrated pipeline: it reads
Module A's harvested chunks from a database table, classifies them (regex →
sanitize → LLM), writes the security-knowledge keepers to a queue for Module C,
and reports a JSON summary. Builds on the Stage 1/1.5/2 code from Weeks 1–4.

What's added

  • DB models (application/database/db.py):
    • harvest_input — Module A writes harvested chunks here (JSONB payload +
      pipeline_run_id + status); Module B reads.
    • knowledge_queue — Module B writes classified keepers here (deduped on
      content_hash); Module C reads.
  • queue_writer.py — maps a verdict to a knowledge_queue row, source-type
    aware, deduped on content_hash; NOISE dropped, KNOWLEDGE/UNCERTAIN kept.
  • pipeline.py (run_noise_filter) — for a pipeline_run_id: read pending
    harvest_input rows → regex → sanitize → LLM classify → write keepers → mark
    rows processed → return a RunSummary.
  • CLI (cre.py / cre_main.py) — --run_noise_filter --run_id <id> [--noise_filter_dry_run], prints the summary as JSON and exits (the entry
    point the orchestrator invokes; exit code = completion signal).
  • Alembic migration d4e5f6a7b8c9 — creates the two tables (down_revision
    c7d8e9f0a1b2).

Behavior

  • Recall-first preserved end to end: only NOISE is dropped; KNOWLEDGE and
    UNCERTAIN always reach the queue.
  • Idempotent: input rows marked processed/error; re-running a run_id is
    safe; UNIQUE(content_hash) collapses duplicate content.
  • Error isolation: unparseable input row → error (not fatal); failed LLM batch
    → those chunks become UNCERTAIN (never dropped); infra failure → non-zero exit.

Testing

  • 10 new unit tests (queue_writer + pipeline) against in-memory SQLite; Module B
    suite 95/95, black --check clean.
  • Verified end-to-end on PostgreSQL: full flask db upgrade from an empty DB
    builds the schema through our head; a real run (cre.py --run_noise_filter)
    classifies a mixed batch, writes KNOWLEDGE rows to knowledge_queue, and exits
    0 with a JSON summary.

Notes

  • The classifier/schemas stay DB-free; queue_writer is the only DB boundary.
  • No pgvector/ML dependency added — Module B needs only litellm (slim prod reqs).

@coderabbitai

coderabbitai Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: ac5c144c-6ab0-475a-a74a-ee50e3efc9b3

📥 Commits

Reviewing files that changed from the base of the PR and between f56cf1f and 51aa2b6.

📒 Files selected for processing (1)
  • application/utils/noise_filter/queue_writer.py

Summary by CodeRabbit

  • New Features
    • Added a Module B noise-filtering workflow to classify harvested content into knowledge, uncertain, or noise.
    • Added CLI options to run by pipeline run ID, produce JSON run summaries, and support dry-run mode.
    • Added a persistent input/output queue with deduplication and source/provenance metadata.
  • Database
    • Added a migration introducing the required tables for Module B processing.
  • Tests
    • Added unit tests covering the happy path, dry runs, parse failures, run scoping, source mapping, and deduplication behavior.

Walkthrough

Changes

Module B noise-filter pipeline

Layer / File(s) Summary
Module B persistence contracts
application/database/db.py, migrations/versions/...
Adds harvest_input and knowledge_queue models and migration tables with status tracking, provenance, JSON payloads, deduplication, and consumption metadata.
Queue writing and verdict mapping
application/utils/noise_filter/queue_writer.py, application/tests/noise_filter/queue_writer_test.py
Filters noise verdicts, maps GitHub and RSS records into queue rows, deduplicates content hashes, and tests persistence behavior.
Noise-filter orchestration
application/utils/noise_filter/pipeline.py, application/tests/noise_filter/pipeline_test.py
Processes pending inputs through parsing, sanitization, regex filtering, LLM classification, queue insertion, status updates, and dry-run handling.
CLI dispatch
cre.py, application/cmd/cre_main.py
Adds noise-filter command options and dispatches runs using a required run ID, database connection, optional dry-run mode, and JSON output.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

  • OWASP/OpenCRE#913: Adds the ChangeRecord and content-hashing components consumed by the new pipeline and queue writer.
  • OWASP/OpenCRE#947: Introduces the LLM classifier components consumed by the new Module B pipeline.

Suggested reviewers: northdpole, paoga87, robvanderveer, pa04rth

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: new harvest_input and knowledge_queue models plus pipeline support.
Description check ✅ Passed The description accurately describes the added models, queue writer, pipeline, CLI, and migration.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
application/utils/noise_filter/pipeline.py (1)

34-47: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

RunSummary.status is hardcoded to "ok" and never reflects run outcome.

The field is initialized once and never updated (e.g., to signal partial failure when parse_errors > 0), so callers parsing the JSON summary can't distinguish a clean run from one with parse errors except by separately checking parse_errors. Either drop the unused field or set it meaningfully (e.g., "partial" when parse_errors or dropped rows are non-zero).

🤖 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 `@application/utils/noise_filter/pipeline.py` around lines 34 - 47, Update
RunSummary.status so it reflects the run outcome instead of remaining hardcoded
to "ok"; set it to the established partial-failure value when parse_errors or
dropped_noise is non-zero, while preserving "ok" for clean runs, or remove the
field entirely if no meaningful status handling exists.
cre.py (1)

304-318: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Inconsistent CLI validation UX vs. --export/--csv.

--export without --csv is validated inline with parser.error(...) (clean usage message, exit 2). --run_noise_filter without --run_id is instead validated inside cre_main.run() by raising ValueError, which surfaces as an unhandled traceback. Consider mirroring the --export pattern here for a consistent CLI experience.

♻️ Suggested fix
     args = parser.parse_args()
     if args.export and not args.csv:
         parser.error("--export requires --csv <path>")
+    if args.run_noise_filter and not args.run_id.strip():
+        parser.error("--run_noise_filter requires --run_id <pipeline_run_id>")
🤖 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 `@cre.py` around lines 304 - 318, Validate the --run_noise_filter and --run_id
dependency during CLI argument parsing, alongside the existing --export/--csv
validation, using parser.error(...) when --run_noise_filter is set without a
nonempty --run_id. Remove or bypass the corresponding ValueError validation in
cre_main.run() so invalid CLI input produces the standard usage error instead of
an unhandled traceback.
application/database/db.py (1)

275-277: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Status comment omits the error state actually used by the pipeline.

pipeline.py sets row.status = "error" for rows that fail ChangeRecord validation, but this comment only documents pending | processed. Update the comment (and ideally add a comment/constraint enumerating all three values) to keep the state machine documented accurately.

📝 Suggested fix
     status = sqla.Column(
         sqla.String, nullable=False, default="pending"
-    )  # pending | processed
+    )  # pending | processed | error
🤖 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 `@application/database/db.py` around lines 275 - 277, Update the status
documentation on the status column in the database model to enumerate all
pipeline states: pending, processed, and error. If an existing constraint or
state declaration is present nearby, keep it synchronized with these three
values without changing the pipeline behavior.
🤖 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 `@application/utils/noise_filter/queue_writer.py`:
- Around line 81-104: Update write_verdicts() to use database-level idempotent
insertion for content_hash, such as PostgreSQL ON CONFLICT DO NOTHING, instead
of relying on the existing pre-query and in-memory deduplication. Ensure
concurrent duplicate hashes are skipped without aborting the transaction or
losing unrelated batch inserts, while preserving the existing WriteStats counts.

---

Nitpick comments:
In `@application/database/db.py`:
- Around line 275-277: Update the status documentation on the status column in
the database model to enumerate all pipeline states: pending, processed, and
error. If an existing constraint or state declaration is present nearby, keep it
synchronized with these three values without changing the pipeline behavior.

In `@application/utils/noise_filter/pipeline.py`:
- Around line 34-47: Update RunSummary.status so it reflects the run outcome
instead of remaining hardcoded to "ok"; set it to the established
partial-failure value when parse_errors or dropped_noise is non-zero, while
preserving "ok" for clean runs, or remove the field entirely if no meaningful
status handling exists.

In `@cre.py`:
- Around line 304-318: Validate the --run_noise_filter and --run_id dependency
during CLI argument parsing, alongside the existing --export/--csv validation,
using parser.error(...) when --run_noise_filter is set without a nonempty
--run_id. Remove or bypass the corresponding ValueError validation in
cre_main.run() so invalid CLI input produces the standard usage error instead of
an unhandled traceback.
🪄 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: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: efb18730-0a64-41ab-87d7-358a43ab2162

📥 Commits

Reviewing files that changed from the base of the PR and between a55e380 and f56cf1f.

📒 Files selected for processing (8)
  • application/cmd/cre_main.py
  • application/database/db.py
  • application/tests/noise_filter/pipeline_test.py
  • application/tests/noise_filter/queue_writer_test.py
  • application/utils/noise_filter/pipeline.py
  • application/utils/noise_filter/queue_writer.py
  • cre.py
  • migrations/versions/d4e5f6a7b8c9_add_module_b_tables.py

Comment thread application/utils/noise_filter/queue_writer.py Outdated
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.

1 participant