Skip to content

fix(config): validate runtime settings before startup side effects - #78

Open
rmems wants to merge 5 commits into
mainfrom
fix/67-validate-runtime-config
Open

rmems wants to merge 5 commits into
mainfrom
fix/67-validate-runtime-config

Conversation

@rmems

@rmems rmems commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

User description

Closes #67

Summary

  • Add one public, side-effect-free DaemonConfig::validate() gate used by TOML loading, daemon constructors, and checkpoint restoration. Timed and bounded runs now require valid configuration at construction, rather than checking tick frequency after startup.
  • Enforce the existing tick range 1..=1_000_000, checked neuron-count arithmetic and 1..=65_535 total neurons, nonzero channels bounded by ingress.max_payload_len, and a documented cap of 1,048,576 neuron×channel slots. Reject multiplication overflow without allocating a network. Preserve simulation with either neuron type and the supported LIF-only live checkpoint path.
  • Validate ingress settings, control bind syntax, PUB host syntax and bounded PUB settings before the binary creates its runtime, restores a checkpoint, initializes sources, or binds sockets. Keep the default stub independent of libzmq. Print the full validation cause in CLI startup errors.
  • Document tightened configuration contracts and migration, including the raw-serde/custom-backend responsibility boundary. Retain exit status 1 and provide explicit bounded systemd restart guidance (RestartSec=5s, three starts per 60 seconds), rather than claiming that earlier rejection alone stops restart loops.
  • Add CLI and public-entry-point regressions and preserve minimal simulation/boundary and existing live-fixture coverage. Update two legacy TOML test fixtures to explicitly request simulation when using Izhikevich cells.
  • Add an idempotent .agents/setup because the fresh orb lacked Rust; it installs the repository-pinned toolchain/components and optional ZeroMQ build prerequisites without changing toolchain pins or default features.

Verification

All checks passed locally on Rust 1.98.1 / Linux:

  • cargo fmt --check — clean.
  • cargo clippy --locked --all-targets -- -D warnings — zero warnings.
  • cargo build --locked — passed.
  • cargo test --locked — 156 unit tests and the CLI integration test passed; the existing process-wide SIGTERM test remains intentionally ignored.
  • CC=gcc CXX=g++ cargo clippy --locked --all-targets --all-features -- -D warnings — zero warnings.
  • CC=gcc CXX=g++ cargo build --locked --all-features — passed.
  • CC=gcc CXX=g++ cargo test --locked --all-features — 178 unit tests, the CLI integration test, and all 9 Thalamic smoke tests passed; the same existing SIGTERM test remains ignored.
  • Real CLI regressions hold a bind port occupied and use a missing checkpoint: invalid tick rate/dimensions/live mode/endpoints exit 1 with the offending field before runtime logging, checkpoint failures, or bind errors.
  • Minimal 1-neuron/1-channel simulation CLI with corpus-ipc stayed running and handled SIGTERM with exit 0.
  • Extracted README service example passed systemd-analyze verify --man=no using the built binary as ExecStart. This verifies syntax, not a live systemd restart cycle.
  • .agents/setup passed bash -n and two executions (warm run ~0.4 seconds); a clean login shell finds Rust 1.98.1.
  • git diff --check — clean.

Regression tests were observed failing before the fixes (invalid tick rate accepted at load, CLI hiding the cause, malformed bracketed IPv4 PUB host accepted).

Release qualification / scope

Part of 02 — v0.3.0 release qualification. Local acceptance work is complete; the unchanged GitHub Actions matrix will verify Linux/macOS/Windows default builds and Linux corpus-ipc on this PR. No merge or release is performed.

Validation cannot undo side effects in a backend pair already constructed by a library caller; callers can invoke validate() first. Host syntax validation does not perform DNS resolution or guarantee that a syntactically valid bind address is available. Invalid configuration still exits 1, so supervisors must use the documented restart/start limits.

Devin Review


Summary by cubic

Moves all runtime configuration validation to a single public DaemonConfig::validate() gate that runs before any network allocation, checkpoint read, backend or socket startup, so invalid settings fail at load or construction instead of after startup.

  • Enforces tick rate 1..=1_000_000, neuron total 1..=65_535, nonzero channels bounded by ingress.max_payload_len, and a MAX_NETWORK_INPUTS cap of 1,048,576 neuron×channel slots with checked arithmetic and operand details on overflow.
  • Validates ingress settings, control_bind syntax, and PUB bind host/options early; digit-and-dot-only names that are malformed IPv4 literals (for example 5555 or 999.999.999.999) are rejected before socket startup, while numeric-TLD hostnames like pub.example.123 stay accepted. CLI errors print the full offending field.
  • Splits validation into focused helpers (validate_dimensions, validate_pub_bind_host, is_dns_label) and reorganizes tests into table-driven fixtures; no behavior change.
  • Adds an idempotent .agents/setup for the pinned Rust toolchain and build prerequisites, including curl for the rustup bootstrap, and documents the tightened config contracts, migration steps, and bounded systemd restart guidance.

Written for commit aae8ecb. Summary will update on new commits.

View guided diff Turn on auto-fix


CodeAnt-AI Description

Reject invalid daemon settings before startup

What Changed

  • Settings are checked before checkpoint access, network creation, backend setup, or socket startup. Invalid tick rates, ingress settings, and control or PUB bind addresses now fail early.
  • Neuron and channel limits are checked together; overflow and networks exceeding 1,048,576 neuron-channel slots are rejected before allocation. Live mode continues to require LIF-only networks.
  • The CLI reports the validation cause and exits with status 1. The configuration guide now explains the limits and bounded systemd restart guidance.

Impact

✅ Invalid settings fail before socket or checkpoint startup
✅ Oversized networks are rejected before allocation
✅ Startup errors identify the invalid setting

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

Centralize validation for TOML, public daemon constructors, and checkpoint
restore. Bound input dimensions with checked arithmetic, validate endpoints
and ingress early, preserve useful CLI diagnostics, and document bounded
restart behavior. Cover invalid startup and supported boundary configs.

Closes #67

Amp-Thread-ID: https://ampcode.com/threads/T-01a11df5-50f4-7582-aa92-9771fb2d3088
Co-authored-by: Raul Cardenas Montoya <montoyaraul34@gmail.com>
@rmems rmems added bug Something isn't working testing core labels Oct 9, 2026
@rmems rmems self-assigned this Oct 9, 2026
@codeant-ai

codeant-ai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Incremental review completed 924293a Oct 12, 2026 · 02:31 02:32
✅ Reviewed your PR 2b0be1a Oct 09, 2026 · 00:11 00:14

@codeant-ai

codeant-ai Bot commented Oct 9, 2026

Copy link
Copy Markdown

Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@coderabbitai

coderabbitai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Essentials
  • Run ID: 541d0115-7270-4c81-a98f-4c02803500e3

📥 Commits

Reviewing files that changed from the base of the PR and between eb003c9 and aae8ecb.


📒 Files selected for processing (1)
  • src/config.rs

Included review availability: This review used your included allowance. 0 included reviews remain after this review. Your included PR review attempts over the past 7 days set your current allowance at 5 reviews per hour.



📝 Summary

Summary by CodeRabbit

  • New Features
    • Configuration checks now run during loading and construction, covering tick rates, network dimensions, inputs, addresses, and other settings. Invalid configurations fail before runtime startup.
  • Bug Fixes
    • Configuration errors now provide more detail, including the affected field. The daemon exits without starting its control listener when configuration is invalid.
  • Documentation
    • Added configuration limits, validation behavior, and migration guidance.
    • Expanded systemd guidance for restart delays, start limits, and troubleshooting repeated failures.

Walkthrough

Daemon configuration validation now runs during loading, construction, and checkpoint restoration. Invalid settings fail before startup proceeds. The CLI reports configuration errors, and documentation describes validation timing and systemd restart handling. A Rust development setup script is also added.

Changes

Configuration Validation

Layer / File(s) Summary
Validation rules and coverage
src/config.rs
DaemonConfig::validate checks tick rate, dimensions, input slots, ingress settings, runtime mode, logging, and bind addresses. Tests cover invalid configurations and supported boundaries across entry points.
Construction and checkpoint validation
src/daemon.rs, src/checkpoint/mod.rs
Daemon construction and network restoration use full configuration validation. Live checkpoint loading no longer separately rejects a nonzero izh_count.
Startup errors and configuration guidance
src/bin/brainstem_daemon.rs, tests/config_startup.rs, README.md, docs/health.md
The CLI prints chained configuration-load errors. Regression tests check invalid startup configurations. The documentation describes validation timing, error handling, and systemd restart limits.

Development Setup

Layer / File(s) Summary
Environment setup
.agents/setup
The script installs missing Debian packages, installs Rustup when needed, installs the configured Rust toolchain with rustfmt and clippy, and fetches locked dependencies.

Priority: ⬆️ High

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

Change: Bug fix · Severity of issue fixed: Medium

Suggested labels: documentation


Merge Risk: ⚪ Minimal · up to aae8e

Invalid configuration is rejected before substantive startup work, and this review found no concrete issue that should block merging.

Pre-merge checks | Passed 3 | Failed 1 | Inconclusive 1

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 67.74% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 31 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Linked Issues check Inconclusive Issue [#67] coding requirements are implemented in the reviewed changes. DaemonConfig::validate() checks tick rate, dimensions, checked arithmetic, channel limits, ingress settings, runtime mode, an… Provide completed GitHub Actions results for the default build matrix and the Linux corpus-ipc job, or otherwise provide reviewable evidence that both required CI paths are green.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check Passed The description clearly explains the validation changes, affected startup paths, tests, documentation, and setup script. It is directly related to the changeset.
Title check Passed The title concisely and accurately summarizes the primary change: validating runtime settings before startup side effects.
Out of Scope Changes check Passed The changes stay within issue [#67]. Validation code, startup ordering, checkpoint handling, CLI error reporting, regression tests, configuration documentation, fixture updates, and systemd guidance d…

Full details: Linked Issues check

Explanation

Issue [#67] coding requirements are implemented in the reviewed changes. DaemonConfig::validate() checks tick rate, dimensions, checked arithmetic, channel limits, ingress settings, runtime mode, and bind settings. DaemonConfig::load(), daemon constructors, and restore_network() call the gate. The changes retain explicit simulation mode and the LIF-only live checkpoint path. README and health documentation describe configuration errors and bounded restart behavior. The reported default and all-features local tests include the corpus-ipc smoke tests. However, the PR states that the GitHub Actions default and corpus-ipc matrix was not yet reported as complete, so the issue requirement that this CI remains green is not established.


  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR






✨ Simplify code
  • Commit to this branch
  • Create a new PR

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@codeant-ai codeant-ai Bot added the size:L This PR changes 100-499 lines, ignoring generated files label Oct 9, 2026

@amazon-q-developer amazon-q-developer 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.

This PR successfully centralizes configuration validation into a single DaemonConfig::validate() method, improving the fail-fast behavior and error reporting. The refactoring properly validates all runtime settings before any side effects occur (network allocation, checkpoint reading, backend/socket initialization).

Key improvements verified:

  • Consolidated validation logic prevents scattered checks and ensures consistent validation across all entry points
  • Comprehensive validation of tick rate, neuron counts, channel dimensions, ingress settings, bind addresses, and PUB socket options
  • Checked arithmetic prevents overflow without allocation
  • Clear error messages that identify the offending configuration field
  • Extensive test coverage including boundary cases and regression tests

All changes function correctly with no defects identified.


You can now have the agent implement changes and create commits directly on your pull request's source branch. Simply comment with /q followed by your request in natural language to ask the agent to make changes.

codescene-access[bot]

This comment was marked as outdated.

@devin-ai-integration devin-ai-integration 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.

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

@codacy-production

codacy-production Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 44 complexity · -2 duplication

Metric Results
Complexity 44
Duplication -2

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@deepsource-io

deepsource-io Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

DeepSource Code Review

We reviewed changes in 59e8cc3...aae8ecb on this pull request. Below is the summary for the review, and you can see the individual issues we found as inline review comments.

See full review on DeepSource ↗

PR Report Card

Overall Grade   Security  

Reliability  

Complexity  

Hygiene  

Code Review Summary

Analyzer Status Updated (UTC) Details
Rust Oct 12, 2026 2:43a.m. Review ↗
Secrets Oct 12, 2026 2:43a.m. Review ↗

Important

AI Review is run only on demand for your team. We're only showing results of static analysis review right now. To trigger AI Review, comment @deepsourcebot review on this thread.

@codeant-ai

codeant-ai Bot commented Oct 9, 2026

Copy link
Copy Markdown

CodeAnt Nitpicks

1 code suggestion

1. The formatter sends tracing output to stderr, so this stdout-only assertion passes even if startup logs appear before validation and fails to test its stated condition.

Possible bug · tests/config_startup.rs:66

@testdriverai

testdriverai Bot commented Oct 9, 2026

Copy link
Copy Markdown

🔎 Reviewing this PR — driving the app now. This preview updates as I go.

live preview

@codeant-ai

codeant-ai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

CodeAnt PR Risk: Low Risk

  • The PR appears safe to merge; configuration validation now checks dimensions, rates, bind settings, and ingress limits before network restoration or daemon startup.
  • Added unit and CLI tests cover invalid configurations, overflow, supported boundaries, and configuration errors preceding checkpoint or socket failures.

Assessed commit: 924293a1ea9f

Address Codacy method-length findings and CodeScene complexity findings
without weakening validation, changing quality gates, or removing coverage.
Keep generic invalid-config cases separate from live-only Izhikevich policy.

Amp-Thread-ID: https://ampcode.com/threads/T-01a11df5-50f4-7582-aa92-9771fb2d3088
Co-authored-by: Raul Cardenas Montoya <montoyaraul34@gmail.com>
codescene-access[bot]

This comment was marked as outdated.

@cubic-dev-ai cubic-dev-ai 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.

All reported issues were addressed across 8 files

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

Comment thread .agents/setup
Comment thread src/config.rs Outdated
- `is_dns_hostname` now rejects names whose final label is all digits
  (`5555`, `999.999.999.999`), so a mistyped `spine_pub_bind_host` fails
  at the config gate instead of at libzmq bind time under corpus-ipc.
- `.agents/setup` adds `curl` to the checked/installed packages so the
  rustup bootstrap works on minimal Debian/Ubuntu hosts.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SDb3MF62P7yPxKo4tC2TVF
codescene-access[bot]

This comment was marked as outdated.

@coderabbitai coderabbitai Bot added the documentation Improvements or additions to documentation label Oct 12, 2026
Keeps is_dns_hostname under the CodeScene cyclomatic-complexity gate
after the numeric-final-label rule was added. No behavior change.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SDb3MF62P7yPxKo4tC2TVF
Comment thread src/config.rs
codescene-access[bot]

This comment was marked as outdated.

@cubic-dev-ai cubic-dev-ai 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.

All reported issues were addressed across 8 files

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread src/config.rs Outdated
Comment thread src/config.rs Outdated
…ands

- is_dns_hostname rejects only names made of digits and dots (malformed
  IPv4 literals such as 5555 or 999.999.999.999); hostnames with a
  numeric final label like pub.example.123 stay accepted.
- The dimensions multiplication-overflow error now prints lif_count,
  izh_count and channels, matching the checked_add error above it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SDb3MF62P7yPxKo4tC2TVF

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

Code Health Improved (1 files improve in Code Health)

Gates Passed
6 Quality Gates Passed

See analysis details in CodeScene

View Improvements
File Code Health Impact Categories Improved
daemon.rs 5.02 → 5.03 Large Method

Quality Gate Profile: Pay Down Tech Debt
Install CodeScene MCP: safeguard and uplift AI-generated code. Catch issues early with our IDE extension and CLI tool.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working core documentation Improvements or additions to documentation size:L This PR changes 100-499 lines, ignoring generated files testing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(config): validate runtime dimensions and tick rate before startup side effects

3 participants