Skip to content

Comments

feat(gov): initial process resource governor (P1-1 + P1-2 core)#53

Merged
heidi-dang merged 2 commits intomainfrom
feat/w2p1-governor
Feb 19, 2026
Merged

feat(gov): initial process resource governor (P1-1 + P1-2 core)#53
heidi-dang merged 2 commits intomainfrom
feat/w2p1-governor

Conversation

@heidi-dang
Copy link
Owner

Summary

  • Add GOV_APPLY schema with strict linear JSON parser (<=512B payload)
  • Add ACK/NACK codes for validation errors
  • Implement RuleSet POD structures (cpu/mem/pids/rlim/oom_score_adj)
  • Add bounded ingress queue (256 capacity) with backpressure
  • Implement ProcessGovernor with apply loop
  • Implement affinity (sched_setaffinity), nice (setpriority), rlimits (prlimit RLIMIT_NOFILE/RLIMIT_CORE), oom_score_adj
  • Add 20 unit tests for parser

Pass criteria

  • ubuntu/macos/windows build-test PASS
  • governance PASS
  • all unit tests PASS

@gemini-code-assist
Copy link

Summary of Changes

Hello @heidi-dang, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request lays the groundwork for process resource governance within the heidi-kernel. It establishes a structured mechanism for defining and applying resource limits and scheduling policies to individual processes, ensuring system stability and controlled resource utilization. The changes introduce a new message schema, a dedicated parser, and an asynchronous governor service that processes and enforces these rules.

Highlights

  • New Governance Schema and Parser: Introduced a new GOV_APPLY schema for process resource governance, supporting CPU affinity/nice, memory limits, PIDs limits, rlimits (nofile/core), and OOM score adjustment. A strict, linear JSON parser was implemented to handle payloads up to 512 bytes, providing detailed ACK/NACK error codes for validation.
  • Process Governor Implementation: Developed the ProcessGovernor class, which includes an asynchronous apply loop, a bounded ingress queue (256 capacity) with backpressure, and mechanisms to apply governance rules to processes using system calls like sched_setaffinity, setpriority, prlimit, and oom_score_adj.
  • Comprehensive Unit Testing: Added a dedicated suite of 20 unit tests for the GOV_APPLY message parser, ensuring robust handling of various valid and invalid JSON payloads, field parsing, range checks, and error conditions.
Changelog
  • include/heidi-kernel/gov_rule.h
    • Defined data structures for CPU, memory, PIDs, and rlimit policies, along with the GovApplyMsg schema.
    • Introduced AckCode enum for validation responses and declared parse_gov_apply and ack_to_string functions.
  • include/heidi-kernel/process_governor.h
    • Declared the ProcessGovernor class, including its public interface for starting/stopping, enqueuing messages, and retrieving statistics.
    • Defined internal structures and private members for managing the asynchronous rule application loop and process rules.
  • src/governor/CMakeLists.txt
    • Updated the build configuration to include the newly added source files: gov_rule.cpp and process_governor.cpp.
  • src/governor/gov_rule.cpp
    • Implemented the parse_gov_apply function, providing a linear JSON parser for governance messages.
    • Developed helper functions for string and numeric parsing, and the ack_to_string utility.
  • src/governor/process_governor.cpp
    • Implemented the core ProcessGovernor logic, including the asynchronous rule application loop and process liveness checks.
    • Provided system call wrappers for applying CPU affinity, nice values, resource limits (nofile, core), and OOM score adjustments.
  • tests/CMakeLists.txt
    • Modified the test build configuration to compile and link the new test_gov_rule.cpp unit test file.
  • tests/test_gov_rule.cpp
    • Added comprehensive unit tests for the gov_rule parser, verifying correct parsing of various policy messages and handling of invalid inputs and ranges.
Activity
  • No specific review comments or activity have been recorded for this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a process resource governor with a custom JSON parser and platform-specific process control logic. A critical vulnerability exists where throwing string-to-number conversion functions (std::stoi, std::stoll) are used on untrusted input without proper exception handling, potentially leading to a process-wide Denial of Service. Additionally, the implementation has critical issues related to correctness and portability, extensively using Linux-specific APIs despite claiming cross-platform compatibility. There's also a significant logic error in how resource limits are retrieved and applied, a potential memory exhaustion issue due to unbounded growth of the rules map, and opportunities to improve performance by avoiding busy-waiting and reducing code duplication.

Comment on lines 51 to 55
int start = std::stoi(left);
int end = std::stoi(right);
ranges.push_back({start, end});
} else {
int cpu = std::stoi(part);

Choose a reason for hiding this comment

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

security-high high

The use of std::stoi on untrusted input from the affinity string can lead to a Denial of Service. std::stoi throws exceptions (std::invalid_argument, std::out_of_range) when parsing fails or the value is too large. Since these exceptions are not caught in the apply_loop thread, any malformed input will cause the entire process to terminate. Consider using std::from_chars or wrapping these calls in a try-catch block.

Comment on lines 234 to 313
} else if (key == "cpu") {
if (s.empty() || s.front() != '{') {
result.ack = AckCode::NACK_PARSE_ERROR;
result.error_detail = "cpu must be an object";
return result;
}
size_t brace_end = 1;
int depth = 1;
while (brace_end < s.size() && depth > 0) {
if (s[brace_end] == '{') {
depth++;
} else if (s[brace_end] == '}') {
depth--;
}
brace_end++;
}
std::string_view cpu_obj = s.substr(0, brace_end);
s.remove_prefix(brace_end);

cpu_obj = trim(cpu_obj);
if (cpu_obj.front() != '{' || cpu_obj.back() != '}') {
result.ack = AckCode::NACK_PARSE_ERROR;
result.error_detail = "malformed cpu object";
return result;
}
cpu_obj.remove_prefix(1);
cpu_obj.remove_suffix(1);
cpu_obj = trim(cpu_obj);

CpuPolicy cpu_policy;
while (!cpu_obj.empty()) {
std::string cpu_key;
if (!parse_key(cpu_obj, cpu_key)) {
result.ack = AckCode::NACK_PARSE_ERROR;
result.error_detail = "failed to parse cpu sub-key";
return result;
}
if (!consume_colon(cpu_obj)) {
result.ack = AckCode::NACK_PARSE_ERROR;
result.error_detail = "missing colon in cpu object";
return result;
}
if (cpu_key == "affinity") {
std::string val;
if (!parse_string_value(cpu_obj, val)) {
result.ack = AckCode::NACK_PARSE_ERROR;
result.error_detail = "failed to parse affinity value";
return result;
}
cpu_policy.affinity = val;
} else if (cpu_key == "nice") {
int8_t val;
if (!parse_int8_value(cpu_obj, val)) {
result.ack = AckCode::NACK_INVALID_RANGE;
result.error_detail = "nice value out of range (-128 to 127)";
return result;
}
cpu_policy.nice = val;
} else if (cpu_key == "max_pct") {
uint8_t val;
if (!parse_uint8_value(cpu_obj, val)) {
result.ack = AckCode::NACK_INVALID_RANGE;
result.error_detail = "max_pct value out of range (0-255)";
return result;
}
cpu_policy.max_pct = val;
} else {
result.ack = AckCode::NACK_UNKNOWN_FIELD;
result.error_detail = "unknown cpu field: " + cpu_key;
return result;
}

skip_whitespace(cpu_obj);
if (!cpu_obj.empty() && cpu_obj[0] == ',') {
cpu_obj.remove_prefix(1);
cpu_obj = trim(cpu_obj);
}
}
result.msg.cpu = cpu_policy;
has_cpu = true;

Choose a reason for hiding this comment

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

high

The logic for parsing nested JSON objects is duplicated for cpu, mem, pids, and rlim. This makes the code harder to maintain and more prone to errors. For example, the block for parsing the cpu object is nearly identical to the blocks for other policy types. Consider extracting this logic into a helper function. This function could take the string_view of the object's content and a lambda to handle the specific key-value pairs for each policy type. This would significantly reduce code duplication and improve maintainability.

Comment on lines 285 to 291
int8_t val;
if (!parse_int8_value(cpu_obj, val)) {
result.ack = AckCode::NACK_INVALID_RANGE;
result.error_detail = "nice value out of range (-128 to 127)";
return result;
}
cpu_policy.nice = val;

Choose a reason for hiding this comment

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

high

The validation for the nice value is incorrect. It uses parse_int8_value, which only checks if the value fits in an int8_t (-128 to 127). The valid range for a process's nice value on Linux is -20 to 19. The parser should enforce this specific range to prevent errors during application and to provide a more accurate error message.

          int64_t val;
          if (!parse_int_value(cpu_obj, val)) {
            result.ack = AckCode::NACK_PARSE_ERROR;
            result.error_detail = "failed to parse nice value";
            return result;
          }
          if (val < -20 || val > 19) {
            result.ack = AckCode::NACK_INVALID_RANGE;
            result.error_detail = "nice value out of range (-20 to 19)";
            return result;
          }
          cpu_policy.nice = static_cast<int8_t>(val);

Comment on lines 267 to 302
if (getrlimit(RLIMIT_NOFILE, &rl) != 0) {
result.err = errno;
result.error_detail = std::strerror(errno);
return result;
}
}
if (rlim.nofile_hard) {
rl.rlim_max = *rlim.nofile_hard;
} else {
if (getrlimit(RLIMIT_NOFILE, &rl) != 0) {
result.err = errno;
result.error_detail = std::strerror(errno);
return result;
}
}
if (prlimit(pid, RLIMIT_NOFILE, &rl, nullptr) != 0) {
result.err = errno;
result.error_detail = "prlimit RLIMIT_NOFILE: " + std::string(std::strerror(errno));
return result;
}
}

if (rlim.core_soft || rlim.core_hard) {
if (rlim.core_soft) {
rl.rlim_cur = *rlim.core_soft;
} else {
if (getrlimit(RLIMIT_CORE, &rl) != 0) {
result.err = errno;
result.error_detail = std::strerror(errno);
return result;
}
}
if (rlim.core_hard) {
rl.rlim_max = *rlim.core_hard;
} else {
if (getrlimit(RLIMIT_CORE, &rl) != 0) {

Choose a reason for hiding this comment

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

security-medium medium

In apply_rlimit, getrlimit is incorrectly used to retrieve current limits. This results in the governor's limits being applied to the target process instead of the target pid's actual limits, leading to a significant logic error in how resource limits are retrieved and applied. Specifically, the logic at lines 276 and 302 overwrites any previously set rl.rlim_cur with the governor's soft limit, ignoring the user-supplied value. A correct and safer implementation would be to first read the existing limits for the target pid using prlimit(pid, resource, nullptr, &rl), modify them with the provided values, and then set them back in a single prlimit call for each resource type.

  if (rlim.nofile_soft || rlim.nofile_hard) {
    // First, get the current limits for the target process
    if (prlimit(pid, RLIMIT_NOFILE, nullptr, &rl) != 0) {
      result.err = errno;
      result.error_detail = "prlimit get RLIMIT_NOFILE: " + std::string(std::strerror(errno));
      return result;
    }

    // Now, update with new values if they are present
    if (rlim.nofile_soft) {
      rl.rlim_cur = *rlim.nofile_soft;
    }
    if (rlim.nofile_hard) {
      rl.rlim_max = *rlim.nofile_hard;
    }

    // Finally, set the new limits
    if (prlimit(pid, RLIMIT_NOFILE, &rl, nullptr) != 0) {
      result.err = errno;
      result.error_detail = "prlimit set RLIMIT_NOFILE: " + std::string(std::strerror(errno));
      return result;
    }
  }

  if (rlim.core_soft || rlim.core_hard) {
    // First, get the current limits for the target process
    if (prlimit(pid, RLIMIT_CORE, nullptr, &rl) != 0) {
      result.err = errno;
      result.error_detail = "prlimit get RLIMIT_CORE: " + std::string(std::strerror(errno));
      return result;
    }

    // Now, update with new values if they are present
    if (rlim.core_soft) {
      rl.rlim_cur = *rlim.core_soft;
    }
    if (rlim.core_hard) {
      rl.rlim_max = *rlim.core_hard;
    }

    // Finally, set the new limits
    if (prlimit(pid, RLIMIT_CORE, &rl, nullptr) != 0) {
      result.err = errno;
      result.error_detail = "prlimit set RLIMIT_CORE: " + std::string(std::strerror(errno));
      return result;
    }
  }

std::lock_guard<std::mutex> lock(rules_mutex_);
if (result.success) {
stats_.messages_processed++;
rules_[msg.pid] = msg;

Choose a reason for hiding this comment

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

security-medium medium

The rules_ map grows indefinitely as new PIDs are governed, as there is no check against the kMaxRules limit (1024) and no mechanism to remove entries for terminated processes. This can lead to memory exhaustion over time. Enforce the kMaxRules limit and implement a cleanup strategy for dead processes. Additionally, the apply_loop function, where this map is managed, currently uses a busy-wait pattern, which is inefficient and consumes unnecessary CPU cycles. Consider using a std::condition_variable for more efficient queue handling.

Comment on lines 76 to 90
out = std::stoll(std::string(s.substr(0, end)));
s.remove_prefix(end);
return true;
}

bool parse_uint_value(std::string_view& s, uint64_t& out) {
skip_whitespace(s);
if (s.empty() || !is_digit(s[0])) {
return false;
}
size_t end = 0;
while (end < s.size() && is_digit(s[end])) {
end++;
}
out = std::stoull(std::string(s.substr(0, end)));

Choose a reason for hiding this comment

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

security-medium medium

The parse_int_value and parse_uint_value functions use std::stoll and std::stoull, which can throw std::out_of_range exceptions if the numeric string in the payload exceeds the range of a 64-bit integer. Although the payload size is limited, it can still contain numbers large enough to trigger these exceptions. If the caller of parse_gov_apply does not catch them, the process will crash. Using std::from_chars is recommended for exception-safe parsing.

- Add GOV_APPLY schema with strict linear JSON parser (<=512B payload)
- Add ACK/NACK codes for validation errors
- Implement RuleSet POD structures (cpu/mem/pids/rlim/oom_score_adj)
- Add bounded ingress queue (256 capacity) with backpressure
- Implement ProcessGovernor with apply loop
- Implement affinity (sched_setaffinity), nice (setpriority),
  rlimits (prlimit RLIMIT_NOFILE/RLIMIT_CORE), oom_score_adj
- Add 20 unit tests for parser (passes 20/20)
@heidi-dang heidi-dang merged commit 2857f76 into main Feb 19, 2026
4 checks passed
@heidi-dang heidi-dang deleted the feat/w2p1-governor branch February 19, 2026 07:24
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