Skip to content

feat(prism): similarity precheck API (3/coldkey/UTC day) - #89

Merged
echobt merged 1 commit into
mainfrom
feat/prism-similarity-precheck-api
Aug 8, 2026
Merged

feat(prism): similarity precheck API (3/coldkey/UTC day)#89
echobt merged 1 commit into
mainfrom
feat/prism-similarity-precheck-api

Conversation

@echobt

@echobt echobt commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Add POST /v1/submissions/precheck so miners can dry-run the intake copy gate (same AST/byte logic + same-hotkey/coldkey exclusion) without queuing a submission or renting a Lium pod.
  • Persist attempts in prism_precheck_quota with 3 checks per coldkey per UTC day (hotkey fallback when Owner unknown); 4th call → 429 / precheck_quota_exceeded.
  • Document in docs/PRISM.md + docs/external-miner/; Design deferred (already has runtime copy-gate + daily manual quota).

Test plan

  • cargo test -p prism-pipeline -p prism-challenge --lib (precheck unit + API tests)
  • cargo clippy -p prism-pipeline -p prism-store -p prism-challenge --all-targets -- -D warnings
  • cargo run -p xtask -- loc-cap / external-docs-check
  • CI green
  • Deploy prism-challenge (migration 0016_prism_precheck_quota)
  • Smoke: curl …/v1/submissions/precheck against staging/prod gateway

Summary by CodeRabbit

  • New Features

    • Added an advisory submission precheck endpoint for dry-running copy detection without queuing submissions, using compute resources, or invoking AI services.
    • Returns similarity verdicts, match details, guidance, and quota status.
    • Supports training-only requests that skip copy evaluation.
    • Enforces three precheck attempts per identity per UTC day.
  • Documentation

    • Documented the endpoint, response fields, quota behavior, and troubleshooting guidance.

Let miners dry-run the intake copy gate before burning a 1-max slot or Lium
pod. Cap at 3 checks per coldkey per UTC day so hotkey rotation cannot spam.
@coderabbitai

coderabbitai Bot commented Aug 8, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds POST /v1/submissions/precheck for dry-running the PRISM copy gate. The endpoint uses daily coldkey quotas, metagraph validation, ephemeral candidates, training-only skips, persistent or in-memory quota stores, structured JSON results, tests, and documentation.

Changes

PRISM precheck

Layer / File(s) Summary
Daily quota persistence
crates/db/migrations/0016_prism_precheck_quota.sql, crates/db/src/prism_store.rs, crates/prism-store/src/store.rs, crates/prism-store/src/dbprism.rs
Adds daily quota storage and atomic consumption for database-backed and in-memory stores.
Precheck pipeline and result models
crates/prism-pipeline/Cargo.toml, crates/prism-pipeline/src/lib.rs, crates/prism-pipeline/src/precheck.rs, crates/prism-challenge/src/agentic.rs
Adds quota identities, filtered corpora, ephemeral candidates, copy evaluation, serialized results, tests, and shared helper re-exports.
Precheck API integration
crates/prism-challenge/src/api.rs
Registers the endpoint, validates metagraph membership, consumes quotas, skips training-only requests, evaluates candidates, and tests quota and copy results.
Precheck endpoint documentation
docs/PRISM.md, docs/external-miner/prism.md, docs/external-miner/troubleshoot.md
Documents the endpoint, request and response fields, quota behavior, advisory semantics, and troubleshooting cases.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant PrecheckAPI
  participant PrismStore
  participant PrecheckPipeline
  Client->>PrecheckAPI: POST /v1/submissions/precheck
  PrecheckAPI->>PrismStore: Consume daily quota
  PrismStore-->>PrecheckAPI: Count or exhausted status
  PrecheckAPI->>PrecheckPipeline: Evaluate ephemeral candidate
  PrecheckPipeline-->>PrecheckAPI: PrecheckResult
  PrecheckAPI-->>Client: JSON verdict and quota details
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely identifies the new PRISM similarity precheck API and its three-per-coldkey-per-UTC-day quota.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/prism-similarity-precheck-api

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

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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 `@crates/prism-challenge/src/api.rs`:
- Around line 287-289: Update the endpoint flow around evaluate_copy_precheck to
propagate corpus-loading errors instead of converting them to an empty list:
load recent entries with normal error handling, return an HTTP 500 on failure,
and only consume quota and evaluate the precheck after the corpus loads
successfully.

In `@crates/prism-pipeline/src/precheck.rs`:
- Around line 80-86: Update quota_identity to treat an all-zero coldkey as
absent before selecting PrecheckIdentityKind::Coldkey, falling back to the
trimmed, lowercased hotkey with HotkeyFallback. Add coverage for zero-owner
quota_identity results and API quota behavior ensuring distinct hotkeys do not
share the zero-owner quota key.
🪄 Autofix

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: 3bcdc4f3-5f0d-4446-934e-ec2b57077902

📥 Commits

Reviewing files that changed from the base of the PR and between 8df58ae and c65156b.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (12)
  • crates/db/migrations/0016_prism_precheck_quota.sql
  • crates/db/src/prism_store.rs
  • crates/prism-challenge/src/agentic.rs
  • crates/prism-challenge/src/api.rs
  • crates/prism-pipeline/Cargo.toml
  • crates/prism-pipeline/src/lib.rs
  • crates/prism-pipeline/src/precheck.rs
  • crates/prism-store/src/dbprism.rs
  • crates/prism-store/src/store.rs
  • docs/PRISM.md
  • docs/external-miner/prism.md
  • docs/external-miner/troubleshoot.md

Comment on lines +287 to +289
let recent = st.store.list(None, None, 64).await.unwrap_or_default();
let result = evaluate_copy_precheck(&candidate, &recent, quota);
Json(precheck_json(&result)).into_response()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not return clean when corpus loading fails.

Line 287 converts a store failure into an empty corpus. The endpoint then returns 200 with similar: false after it consumes quota. This is not the same copy gate as intake.

Load the corpus with normal error handling before quota consumption. Return a 500 when loading fails.

Proposed fix
-    let used = match st
+    let recent = match st.store.list(None, None, 64).await {
+        Ok(rows) => rows,
+        Err(e) => return json_err(StatusCode::INTERNAL_SERVER_ERROR, "store", &e.to_string()),
+    };
+    let used = match st
         .store
         .precheck_quota_try_consume(&identity, &day, PRECHECK_DAILY_LIMIT)
         .await
@@
-    let recent = st.store.list(None, None, 64).await.unwrap_or_default();
     let result = evaluate_copy_precheck(&candidate, &recent, quota);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let recent = st.store.list(None, None, 64).await.unwrap_or_default();
let result = evaluate_copy_precheck(&candidate, &recent, quota);
Json(precheck_json(&result)).into_response()
let recent = match st.store.list(None, None, 64).await {
Ok(rows) => rows,
Err(e) => return json_err(StatusCode::INTERNAL_SERVER_ERROR, "store", &e.to_string()),
};
let result = evaluate_copy_precheck(&candidate, &recent, quota);
Json(precheck_json(&result)).into_response()
🤖 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 `@crates/prism-challenge/src/api.rs` around lines 287 - 289, Update the
endpoint flow around evaluate_copy_precheck to propagate corpus-loading errors
instead of converting them to an empty list: load recent entries with normal
error handling, return an HTTP 500 on failure, and only consume quota and
evaluate the precheck after the corpus loads successfully.

Comment on lines +80 to +86
pub fn quota_identity(hotkey: &str, coldkey: Option<&str>) -> (String, PrecheckIdentityKind) {
match coldkey.map(str::trim).filter(|s| !s.is_empty()) {
Some(ck) => (ck.to_ascii_lowercase(), PrecheckIdentityKind::Coldkey),
None => (
hotkey.trim().to_ascii_lowercase(),
PrecheckIdentityKind::HotkeyFallback,
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Treat an all-zero Owner as unknown.

Line 81 accepts a zero coldkey as Coldkey. The documented unknown-owner case must use HotkeyFallback. Otherwise, all hotkeys with a zero Owner share one quota key, so one miner can exhaust another miner's precheck budget.

Filter the all-zero value before the coldkey branch. Add tests for both quota_identity and the API quota behavior.

Proposed fix
 pub fn quota_identity(hotkey: &str, coldkey: Option<&str>) -> (String, PrecheckIdentityKind) {
-    match coldkey.map(str::trim).filter(|s| !s.is_empty()) {
+    match coldkey
+        .map(str::trim)
+        .filter(|s| !s.is_empty() && !s.bytes().all(|b| b == b'0'))
+    {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub fn quota_identity(hotkey: &str, coldkey: Option<&str>) -> (String, PrecheckIdentityKind) {
match coldkey.map(str::trim).filter(|s| !s.is_empty()) {
Some(ck) => (ck.to_ascii_lowercase(), PrecheckIdentityKind::Coldkey),
None => (
hotkey.trim().to_ascii_lowercase(),
PrecheckIdentityKind::HotkeyFallback,
),
pub fn quota_identity(hotkey: &str, coldkey: Option<&str>) -> (String, PrecheckIdentityKind) {
match coldkey
.map(str::trim)
.filter(|s| !s.is_empty() && !s.bytes().all(|b| b == b'0'))
{
Some(ck) => (ck.to_ascii_lowercase(), PrecheckIdentityKind::Coldkey),
None => (
hotkey.trim().to_ascii_lowercase(),
PrecheckIdentityKind::HotkeyFallback,
),
🤖 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 `@crates/prism-pipeline/src/precheck.rs` around lines 80 - 86, Update
quota_identity to treat an all-zero coldkey as absent before selecting
PrecheckIdentityKind::Coldkey, falling back to the trimmed, lowercased hotkey
with HotkeyFallback. Add coverage for zero-owner quota_identity results and API
quota behavior ensuring distinct hotkeys do not share the zero-owner quota key.

@echobt
echobt merged commit 574321a into main Aug 8, 2026
3 checks passed
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