Skip to content

Require num_colors for runtime KColoring JSON - #1248

Open
isPANN wants to merge 4 commits into
mainfrom
fix/kcoloring-num-colors
Open

isPANN wants to merge 4 commits into
mainfrom
fix/kcoloring-num-colors

Conversation

@isPANN

@isPANN isPANN commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

Summary

KColoring<KN, _> silently deserialized a missing num_colors as 0. A JSON instance written with a typo ("k": 4 instead of "num_colors": 4) therefore became a zero-colour problem: its ILP had no variables and pred solve reported infeasible in 0 s — a wrong answer with no error.

  • Runtime-K (KN) JSON now requires num_colors; a missing field is a deserialization error.
  • Fixed-K variants (K2, K3) keep their behaviour: num_colors may be omitted (it equals K) and a mismatched or null value is rejected.
  • Deserialization goes through a try_from data form, the same serde pattern other models use, instead of a field-level default.
  • The previous test that asserted the zero default is replaced by one asserting the error (with and without the k typo).

Unknown fields are still ignored, as for every model except QUBO (deny_unknown_fields); no repo-wide policy exists, so this PR does not introduce one. An audit of #[serde(default ...)] in src/models/ found no other defaults that invent values for required inputs.

Test plan

  • cargo test --workspace: 7205 passed, 0 failed
  • cargo clippy --all-targets: clean for the changed files
  • CLI repro: the typo'd JSON now fails with missing field `num_colors` ; the corrected input solves to [0, 1, 0]

🤖 Generated with Claude Code

isPANN and others added 2 commits November 20, 2026 07:24
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Replace the hand-written Deserialize impl with the repo's serde try_from
pattern; behavior is unchanged (runtime K requires num_colors, fixed K may
omit it, explicit null and mismatched counts are rejected).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.94%. Comparing base (e7bacb3) to head (bd84894).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1248      +/-   ##
==========================================
- Coverage   97.19%   96.94%   -0.26%     
==========================================
  Files        1146     1146              
  Lines      151558   154062    +2504     
==========================================
+ Hits       147308   149351    +2043     
- Misses       4250     4711     +461     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@isPANN

isPANN commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

Agentic Review Report

Reviewed head 7df53b62 (generic PR; 2 files: src/models/graph/kcoloring.rs, src/unit_tests/models/graph/kcoloring.rs). No linked issue.

Verdict: changes requested (one small Important fix). The behaviour change is correct and well-targeted. The one problem is that the new serde conversion uses a bare String error type, which breaks the repo's typed-error rule.

(a) Structural and semantic

  • No generated exports, no unrelated edits, and no core-trait or macro changes. The diff is confined to the KColoring model and its tests.
  • Moving from a field-level default + deserialize_with to a try_from = "KColoringData<G>" data form matches the pattern about 30 other models use.
  • Hand-traced TryFrom<KColoringData<G>> (kcoloring.rs:132-148) for every case:
variant num_colors absent matching mismatched null wrong type (-1, "3")
K2/K3 K (ok) ok error error (deserialize_present) error
KN error (new) ok n/a error error

This matches the PR description. Fixed-K behaviour is unchanged, and KN no longer invents 0.

  • Serialize is still field-wise and always writes num_colors, so every persisted instance and bundle round-trips.
  • The PR body's audit claim holds: #[serde(default appears nowhere else in src/models/. Nothing in the repo feeds KN JSON without num_colors:
    • tests/data/jl/coloring.json is parsed by hand, not through serde.
    • The CLI and MCP fixtures go through pred create, which always emits num_colors.
  • The new error goes through ConstructionError in the registry load path (src/registry/mod.rs:104), which wraps the message as InvalidInput.

(b) Quality

  • The old test asserted the zero default; the new test runtime_coloring_requires_an_explicit_color_count asserts the error for both the bare input and the "k" typo. Good regression coverage.

  • The fixed-K matrix (absent / 0..=6 / usize::MAX / null / -1 / "3") is still exercised by fixed_color_counts_survive_all_serialization_paths.

  • Gap: KN with an explicit null or a wrong-typed num_colors is not tested (see Minor 1).

  • Local runs on the head commit:

    • cargo test --lib kcoloring: 76 passed.
    • cargo test -p problemreductions-cli --features mcp kcoloring: 4 passed (test_create_kcoloring, test_create_kcoloring_missing_k, test_create_random_kcoloring, mcp::tests::test_create_problem_kcoloring).
  • The CI Clippy failure is not caused by this PR. All 10 errors are new rustc/clippy 1.100.0 (2026-11-09) lints in files this PR does not touch:

    • minimum_edge_cost_flow.rs:291
    • minimum_register_sufficiency_for_loops.rs:170
    • rectilinear_picture_compression.rs:207-219
    • ksatisfiability_preemptivescheduling.rs:280
    • unitdiskmapping/grid.rs:176-271

    Local clippy with the same toolchain reports nothing in kcoloring.rs. Main last ran CI on 2026-10-30 with the older toolchain, so main will fail the same way. That needs a separate fix on main. Test, Windows and Code Coverage were still pending at review time.

(c) Feature test

The CLI was built in the review worktree and run from a scratch directory as target/debug/pred. I used this instead of make cli, so the global pred install was not overwritten.

input command result
KN, "k": 4 instead of num_colors pred inspect / pred solve Error: invalid construction input: missing field num_colors`` (previously solved as infeasible)
KN, "num_colors": null pred solve invalid type: null, expected usize
KN, num_colors: 3, 5-vertex graph pred solve, --solver brute-force Or(true) with a valid coloring
K3, num_colors removed pred solve, --solver brute-force loads as 3 colors, Or(true)
K3, num_colors: 2 pred solve fixed K requires 3 colors, got 2
K3, num_colors: null pred solve rejected
pred create --example KColoring/K3 writes num_colors: 3
KN, pred path KColoring ILP then pred reduce --via pred solve bundle.json Or(true) via ILP Min(0); the bundle's persisted source carries num_colors

The default-variant pred create --example KColoring fails because KN has no canonical example. That predates this PR and is out of scope.

Findings

Critical: none.

Important

  1. src/models/graph/kcoloring.rs:133: type Error = String;. This is now the only type Error = String in src/.
    • .claude/CLAUDE.md requires public construction paths, including registry JSON load, to return ConstructionError, and says no path "returns or creates an error as a bare String".
    • Every sibling try_from data form (e.g. KnapsackData, SubsetSumData, JobShopSchedulingData) uses crate::registry::ConstructionError. The PR body describes this as "the same serde pattern other models use", but this is the one place it differs.
    • Fix: use type Error = crate::registry::ConstructionError;, and write return Err(format!("fixed K requires {fixed} colors, got {supplied}").into()); at line 138. The existing From<&str> impl already covers the ok_or(...)? at line 140.
    • The new test's contains("missing field num_colors") assertion still holds after the change.

Minor

  1. src/unit_tests/models/graph/kcoloring.rs:313-322: the KN test covers only the absent-field and typo cases.
    • The null branch that deserialize_present (kcoloring.rs:121-130) was added for is tested only through K2/K3.
    • Fix: add json!({"graph": ..., "num_colors": null}) and a "3" string case for KColoring<KN, SimpleGraph>, and assert both are errors.
  2. docs/paper/reductions.typ:2827 says only "The KN variant stores its color count at runtime."
    • Fix (optional): add that a persisted KN instance must carry num_colors, while fixed variants may omit it. This would document the new contract next to the existing fixed-K sentence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@isPANN

isPANN commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the Important finding: the TryFrom<KColoringData<G>> conversion now uses crate::registry::ConstructionError like the other data-form models (6cb6e12). cargo test --lib kcoloring: 76 passed. The Clippy CI failure comes from new 1.100 lints in files this PR doesn't touch; main has the same failure.

Address needless_bool and needless_range_loop lints that the updated
stable toolchain reports on existing code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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