Skip to content

Remove dead C backend code#8

Merged
cardil merged 6 commits into
mainfrom
cleanup/dead-code-removal
Mar 1, 2026
Merged

Remove dead C backend code#8
cardil merged 6 commits into
mainfrom
cleanup/dead-code-removal

Conversation

@cardil
Copy link
Copy Markdown
Owner

@cardil cardil commented Mar 1, 2026

Audited the C backend against frontend API usage. The frontend is the only consumer of the C backend API. All active endpoints are used — no dead endpoints were found.

However, src/request.c contained dead internal code that accumulated over time:

Removed

Dead globals

  • mesh_matrix[] — 3D visualizer buffer, never read by any API response
  • mesh_values[] — double array for parsed mesh values, unused externally
  • probe_count_x, probe_count_y — set from config but never read
  • x_count, y_count — set from config but never read

Dead functions

  • mesh_matrix_clear() — only called by dead mesh_matrix_export()
  • mesh_clear() — only called by dead parse_mesh_values()
  • mesh_matrix_export() — formatted mesh matrix for 3D visualizer, never used
  • parse_mesh_values() — parsed mesh into double array; replaced with count_mesh_elements() (counts commas to determine grid size)
  • get_ssh_status() — duplicate; api.c has its own inline SSH process scan

Dead macros

  • MAX_DATA_SLOTS
  • MIN_SUPPORTED_GRID_SIZE
  • MESH_MATRIX_ELEMENTS

Net change

-96 lines (106 deleted, 10 added for count_mesh_elements())

All 30 e2e tests pass.

Assisted-by: 🤖 Claude Sonnet 4.6

Summary by CodeRabbit

  • Refactor

    • Streamlined mesh handling and removed legacy 3D mesh export/parsing; grid size now inferred from CSV-style input.
    • Simplified configuration parsing state machine for GET-based uploads.
  • Bug Fixes

    • Improved numeric precision in bed-leveling averages (consistent 6-decimal rounding).
    • Removed obsolete status handling.
  • Chores

    • Silenced unused-parameter warnings and removed unused locals and variables.

- Remove mesh_matrix[] buffer (3d visualizer, never used by API)
- Remove mesh_values[] double array (parsed values, unused)
- Remove mesh_matrix_clear(), mesh_clear(), mesh_matrix_export() functions
- Remove parse_mesh_values() — replaced with count_mesh_elements()
- Remove probe_count_x, probe_count_y, x_count, y_count globals (set but never read)
- Remove get_ssh_status() function (duplicate; api.c has its own inline impl)
- Remove MAX_DATA_SLOTS, MIN_SUPPORTED_GRID_SIZE, MESH_MATRIX_ELEMENTS macros
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 1, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 868ef90 and ed82bc6.

📒 Files selected for processing (2)
  • frontend/src/lib/stores/leveling.ts
  • src/request.c
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/lib/stores/leveling.ts

Walkthrough

Removed legacy mesh scaffolding and public mesh symbols from src/request.c, replaced mesh parsing with a CSV-count helper, and applied small cleanups across the codebase to remove unused variables and tighten parsing/rounding logic in frontend/store.

Changes

Cohort / File(s) Summary
Mesh Handling Simplification
src/request.c
Removed public mesh typedef/macros and buffers (BYTE, MAX_DATA_SLOTS, MIN_SUPPORTED_GRID_SIZE, MESH_MATRIX_ELEMENTS, mesh_values, mesh_matrix), deleted mesh helpers (mesh_matrix_clear, mesh_clear, mesh_matrix_export, parse_mesh_values, get_ssh_status) and probe/count variables; added static mesh_grid_size_from_csv(const char *buffer) and simplified read_mesh_from_config_file() to infer grid size from CSV-like points.
Frontend rounding precision
frontend/src/lib/stores/leveling.ts
Added round6(val: number) and applied 6-decimal clamping in applyPrecision and calculateAverageSlot to limit zOffset precision.
Unused-parameter / minor cleanups
src/api.c, src/webfsd.c, src/webcam.c, src/response.c
Silenced unused-parameter/variable warnings and removed unused locals: (void)filename; in handle_api_request, (void)thread_arg; in mainloop, removed file_size in v_process_image, and removed expires in mkheader. No functional changes.
Config parser simplification
src/config-parser.c
Removed local k_or_v state from read_config_file_from_get_request; logic now relies on existing key/value pointers and boundary checks for parsing.
Minor cleanup in request processing
src/request.c
Removed an unused co variable in process_custom_pages() and kept only config_option_t query local declaration.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐇 I nibble commas, count the rows,
Toss old buffers where no data grows.
A tiny helper finds the grid,
Hops in to keep the code well-rid.
Clean burrow, soft-debugged nose 🥕

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Remove dead C backend code' directly and clearly summarizes the main objective of the PR, which is removing unused functions, variables, macros, and dead code from src/request.c and related files.
Docstring Coverage ✅ Passed Docstring coverage is 93.33% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch cleanup/dead-code-removal

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 and usage tips.

- Remove 257-element GRID[] table (integer sqrt via lookup)
- Remove BYTE typedef (was only used by GRID[])
- Replace count_mesh_elements()+GRID[] with mesh_grid_size_from_csv():
  counts commas, then does a simple integer sqrt loop (n*n==count)
- Result is clearer and 250+ lines shorter
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

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

No issues found across 1 file

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

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 (1)
src/request.c (1)

192-205: Loop upper bound exceeds MAX_SUPPORTED_GRID_SIZE.

The loop iterates up to n = 12, supporting grids up to 12×12 (144 elements), but MAX_SUPPORTED_GRID_SIZE is defined as 10 on line 171. If a valid 11×11 or 12×12 CSV is parsed, mesh_grid would be set to 11 or 12, potentially causing downstream issues when code assumes the grid fits within the 10×10 limit (e.g., buffer sizing via MESH_BUFFER_SIZE).

Consider aligning the loop bound with the macro:

Suggested fix
     // Integer square root: find n such that n*n == count
-    for (int n = 2; n <= 12; n++) {
+    for (int n = 2; n <= MAX_SUPPORTED_GRID_SIZE; n++) {
         if (n * n == count) return n;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/request.c` around lines 192 - 205, The loop in mesh_grid_size_from_csv
currently checks n up to 12, exceeding the project limit MAX_SUPPORTED_GRID_SIZE
and allowing mesh_grid values that may overflow buffers like MESH_BUFFER_SIZE;
change the loop upper bound to use the macro (for (int n = 2; n <=
MAX_SUPPORTED_GRID_SIZE; n++)) so the function only returns grid sizes within
the supported limit, and ensure callers that set mesh_grid use that value
consistently.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/request.c`:
- Around line 248-252: The code uses strcpy(mesh_config, &b[9]) which can
overflow MESH_BUFFER_SIZE when getline() returns a longer line; change the copy
to a bounded copy that respects MESH_BUFFER_SIZE (e.g., use strncpy/strlcpy or
memcpy with an explicit length calculation) and always null-terminate
mesh_config after copy, and validate/truncate the source (&b[9]) length before
calling mesh_grid_size_from_csv if that function expects a full string; update
the block around mesh_config, mesh_grid_size_from_csv, and any use of b to
enforce the buffer limit and prevent overflow.

---

Nitpick comments:
In `@src/request.c`:
- Around line 192-205: The loop in mesh_grid_size_from_csv currently checks n up
to 12, exceeding the project limit MAX_SUPPORTED_GRID_SIZE and allowing
mesh_grid values that may overflow buffers like MESH_BUFFER_SIZE; change the
loop upper bound to use the macro (for (int n = 2; n <= MAX_SUPPORTED_GRID_SIZE;
n++)) so the function only returns grid sizes within the supported limit, and
ensure callers that set mesh_grid use that value consistently.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0bb04fb and c05629d.

📒 Files selected for processing (1)
  • src/request.c

Comment thread src/request.c Outdated
cardil added 3 commits March 1, 2026 17:47
- Replace strcpy with strncpy(MESH_BUFFER_SIZE-1) + null-termination
- Prevents buffer overflow from long lines in config file
- request.c: remove unused 'i' in update_printer_config_file
- request.c: silence unused 'arg' in webcam_capture_thread (pthread signature)
- request.c: remove unused 'co' in process_custom_pages
- api.c: silence unused 'filename' in handle_api_request (handler signature)
- config-parser.c: remove unused 'k_or_v' (set but never read)
- response.c: remove unused 'expires' in mkheader
- webcam.c: remove unused 'file_size' in v_process_image
- webfsd.c: silence unused 'thread_arg' in mainloop (pthread signature)
Average z_offset like 1.4111333333333331 was being written to config.
Klipper expects 6 decimal places (e.g. -1.440000). Add round6() helper
and apply it to avgZOffset and mesh point precision rounding.
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

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 the current code and only fix it if needed.

Inline comments:
In `@frontend/src/lib/stores/leveling.ts`:
- Around line 51-53: The current round6 function uses Math.round which
implements asymmetric tie-breaking for negatives and thus doesn't match the C
backend's round() (which rounds half away from zero); update round6 to perform
symmetric half-away-from-zero rounding at the 1e-6 scale by multiplying val by
1e6, taking the absolute value, adding 0.5 and flooring to get the rounded
magnitude, then reapply the original sign and divide by 1e6 so that halfway
values (e.g., -1.500000) round away from zero like C's round(); ensure this
change is applied in the round6 function.

In `@src/request.c`:
- Around line 201-203: The mesh-size detection loop that tests for n*n == count
must be bounded and must validate the stored/truncated grid size consistently:
clamp or reject any computed size > MAX_SUPPORTED_GRID_SIZE (use
MAX_SUPPORTED_GRID_SIZE in the check where you compute/derive size from count),
compute count from the same bounded/truncated buffer used for storage (so the
value used in the for loop and the stored size copy are consistent), and
explicitly fail (return error/false) if the computed size is 0 or >
MAX_SUPPORTED_GRID_SIZE rather than marking success; update the loop/validation
around the code that uses count, n, MAX_SUPPORTED_GRID_SIZE and the stored size
variable so parsing only succeeds when size is non-zero, <=
MAX_SUPPORTED_GRID_SIZE, and n*n == count.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c05629d and 868ef90.

📒 Files selected for processing (7)
  • frontend/src/lib/stores/leveling.ts
  • src/api.c
  • src/config-parser.c
  • src/request.c
  • src/response.c
  • src/webcam.c
  • src/webfsd.c
💤 Files with no reviewable changes (2)
  • src/response.c
  • src/webcam.c

Comment thread frontend/src/lib/stores/leveling.ts
Comment thread src/request.c Outdated
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

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

1 issue found across 7 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="src/request.c">

<violation number="1" location="src/request.c:248">
P2: After introducing bounded copy with `strncpy`, `mesh_grid_size_from_csv` is still called with the unbounded `&b[9]` rather than the now-bounded `mesh_config`. If the input exceeds `MESH_BUFFER_SIZE`, `mesh_config` will be truncated but `mesh_grid` will be computed from the full untruncated data — creating an inconsistent state where the stored mesh string and the computed grid size don't match. Pass `mesh_config` to the function instead to ensure consistency.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread src/request.c
- leveling.ts: fix round6() to use half-away-from-zero (like C's round())
  instead of Math.round() which rounds negatives toward +infinity
- request.c: use MAX_SUPPORTED_GRID_SIZE in mesh_grid_size_from_csv loop
  instead of magic constant 12
- request.c: validate mesh line length before copying to prevent
  accepting truncated meshes; compute grid size from bounded copy for
  consistency; fail explicitly if grid size is 0
@cardil cardil merged commit d6153d2 into main Mar 1, 2026
4 checks passed
@cardil cardil deleted the cleanup/dead-code-removal branch March 1, 2026 18:35
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