From f690c6d53883d49edcd33999699c0afeafebbd80 Mon Sep 17 00:00:00 2001 From: Cong Wang Date: Sun, 29 Nov 2026 16:45:42 -0800 Subject: [PATCH 1/3] docs: Remove the CPU and NUMA topology document docs/CPU_NUMA_TOPOLOGY.md describes placement policies, a topology section in the baseline and validation warnings as if they worked. None of it does: nothing in kerf writes a topology section, so the policies have nothing to act on. The README repeated the claim in its feature list and in a section of its own. Remove the document and what the README says about it. Per-node pool memory, kerf init --memory=SIZE@N, is a different thing that does work, and stays documented. Signed-off-by: Cong Wang --- README.md | 11 -- docs/CPU_NUMA_TOPOLOGY.md | 328 -------------------------------------- 2 files changed, 339 deletions(-) delete mode 100644 docs/CPU_NUMA_TOPOLOGY.md diff --git a/README.md b/README.md index 11e2405..eb1c606 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,6 @@ Every resource is described in a device tree that the host kernel holds. `kerf` - [Command Guide](#command-guide) - [How It Works](#how-it-works) - [Validation Rules](#validation-rules) -- [CPU and NUMA Topology](#cpu-and-numa-topology) - [References](#references) ## Features @@ -26,7 +25,6 @@ Every resource is described in a device tree that the host kernel holds. `kerf` - **Signing and lockdown**: sign spawn kernels, and lock them down per run - **Access to running instances**: run commands inside an instance or attach to its console - **Inspection and replay**: show instances, list CPUs, and dump the device tree to replay it later or on another host -- **CPU and NUMA awareness**: topology-aware CPU and memory placement ## Installation @@ -384,15 +382,6 @@ All `kerf` operations validate automatically, against the full state (baseline p 2. All phandle references must resolve 3. Baseline resource configuration must be complete and consistent -## CPU and NUMA Topology - -- **CPU topology**: socket, core, and thread mapping with SMT/hyperthreading support -- **NUMA awareness**: NUMA node definition with memory regions and CPU assignments -- **Topology policies**: CPU affinity (`compact`, `spread`, `local`) and memory policies (`local`, `interleave`, `bind`) -- **Performance validation**: automatic validation of topology constraints and performance warnings - -For details, see [CPU_NUMA_TOPOLOGY.md](docs/CPU_NUMA_TOPOLOGY.md). - ## References - **Device Tree Specification**: https://devicetree-specification.readthedocs.io/ diff --git a/docs/CPU_NUMA_TOPOLOGY.md b/docs/CPU_NUMA_TOPOLOGY.md deleted file mode 100644 index ede2c93..0000000 --- a/docs/CPU_NUMA_TOPOLOGY.md +++ /dev/null @@ -1,328 +0,0 @@ -# CPU and NUMA Topology Support in Kerf - -## Overview - -Kerf now provides comprehensive support for CPU and NUMA topology management in multikernel systems. This enables optimal resource allocation based on hardware topology, ensuring that kernel instances are placed on appropriate CPUs and memory regions for maximum performance. - -## Key Features - -### 1. CPU Topology Awareness -- **Socket identification**: Track which socket each CPU belongs to -- **Core mapping**: Understand CPU core relationships and SMT/hyperthreading -- **Cache hierarchy**: Model CPU cache levels and sizes -- **NUMA node association**: Map CPUs to their NUMA nodes - -### 2. NUMA Topology Support -- **NUMA node definition**: Specify memory regions and CPU assignments per NUMA node -- **Distance matrix**: Model NUMA node distances for optimal placement -- **Memory types**: Support different memory types (DRAM, HBM, CXL) -- **Memory locality**: Ensure memory and CPU allocations are co-located - -### 3. Topology-Aware Allocation Policies -- **CPU affinity**: `compact`, `spread`, `local` policies for CPU placement -- **Memory policy**: `local`, `interleave`, `bind` policies for memory allocation -- **NUMA constraints**: Specify preferred NUMA nodes for instances -- **Performance optimization**: Automatic validation of topology constraints - -## Device Tree Format - -### Basic NUMA Topology - -```dts -resources { - cpus { - total = <32>; - host-reserved = <0 1 2 3>; - available = <4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 - 20 21 22 23 24 25 26 27 28 29 30 31>; - }; - - topology { - numa-nodes { - node@0 { - node-id = <0>; - memory-base = <0x0 0x0>; - memory-size = <0x0 0x800000000>; // 16GB - cpus = <0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15>; - }; - - node@1 { - node-id = <1>; - memory-base = <0x0 0x800000000>; - memory-size = <0x0 0x800000000>; // 16GB - cpus = <16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31>; - }; - }; - }; -}; -``` - -### Advanced CPU Topology - -```dts -resources { - cpus { - total = <32>; - host-reserved = <0 1 2 3>; - available = <4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 - 20 21 22 23 24 25 26 27 28 29 30 31>; - - // CPU core topology (SMT/Hyperthreading) - cores { - // Socket 0, NUMA node 0 cores - core@0 { cpus = <0 1>; }; // SMT siblings - core@1 { cpus = <2 3>; }; - core@2 { cpus = <4 5>; }; - core@3 { cpus = <6 7>; }; - // ... more cores ... - }; - }; - - topology { - numa-nodes { - node@0 { - node-id = <0>; - memory-base = <0x0 0x0>; - memory-size = <0x0 0x800000000>; - cpus = <0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15>; - }; - - node@1 { - node-id = <1>; - memory-base = <0x0 0x800000000>; - memory-size = <0x0 0x800000000>; - cpus = <16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31>; - }; - }; - }; -}; -``` - -### Instance Topology Configuration - -```dts -instances { - web-server { - id = <1>; - resources { - cpus = <4 5 6 7 8 9 10 11>; // NUMA node 0 - memory-base = <0x0 0x800000000>; - memory-bytes = <0x0 0x200000000>; // 8GB - numa-nodes = <0>; // Preferred NUMA nodes - cpu-affinity = "compact"; // CPU placement policy - memory-policy = "local"; // Memory allocation policy - devices = <ð0_vf1>; - }; - }; - - database { - id = <2>; - resources { - cpus = <20 21 22 23 24 25 26 27>; // NUMA node 1 - memory-base = <0x0 0x800000000>; - memory-bytes = <0x0 0x400000000>; // 16GB - numa-nodes = <1>; - cpu-affinity = "compact"; - memory-policy = "local"; - devices = <ð1_vf1>; - }; - }; - - compute { - id = <3>; - resources { - cpus = <12 13 14 15 16 17 18 19 28 29 30 31>; // Cross-NUMA - memory-base = <0x0 0xA00000000>; - memory-bytes = <0x0 0x200000000>; // 8GB - numa-nodes = <0 1>; // Multiple NUMA nodes - cpu-affinity = "spread"; // Spread across NUMA nodes - memory-policy = "interleave"; // Interleave memory allocation - }; - }; -}; -``` - -## CPU Affinity Policies - -### `compact` -- **Purpose**: Minimize NUMA node crossings and maximize cache locality -- **Behavior**: Allocates CPUs from the same NUMA node and preferably the same core -- **Use case**: High-performance, latency-sensitive workloads -- **Example**: Database workloads, real-time applications - -### `spread` -- **Purpose**: Distribute workload across multiple NUMA nodes -- **Behavior**: Allocates CPUs from different NUMA nodes -- **Use case**: Throughput-oriented workloads that can benefit from parallel processing -- **Example**: Batch processing, analytics workloads - -### `local` -- **Purpose**: Co-locate CPUs and memory on the same NUMA node -- **Behavior**: Ensures CPUs and memory are from the same NUMA node -- **Use case**: Memory-intensive workloads requiring low latency access -- **Example**: In-memory databases, high-performance computing - -## Memory Policies - -### `local` -- **Purpose**: Allocate memory from the same NUMA node as CPUs -- **Behavior**: Ensures memory is local to the CPU cores -- **Use case**: Performance-critical applications -- **Benefits**: Lowest memory access latency - -### `interleave` -- **Purpose**: Distribute memory allocation across multiple NUMA nodes -- **Behavior**: Memory is allocated from different NUMA nodes -- **Use case**: Large memory allocations that exceed single NUMA node capacity -- **Benefits**: Higher total memory bandwidth - -### `bind` -- **Purpose**: Bind memory allocation to specific NUMA nodes -- **Behavior**: Memory is allocated only from specified NUMA nodes -- **Use case**: Workloads with specific memory requirements -- **Benefits**: Predictable memory placement - -## Validation and Error Detection - -Kerf automatically validates topology constraints and provides detailed error messages: - -### NUMA Constraint Validation -``` -ERROR: Instance database: NUMA node 3 does not exist in hardware topology -WARNING: Instance web-server: CPU 8 is in NUMA node 1, but instance is configured for NUMA nodes [0]. This may cause performance issues due to remote memory access. -``` - -### CPU Affinity Validation -``` -WARNING: Instance compute: Compact CPU affinity requested but CPUs span multiple NUMA nodes: [0, 1] -WARNING: Instance analytics: Spread CPU affinity requested but CPUs are from single NUMA node 0 -``` - -### Memory Policy Validation -``` -WARNING: Instance database: Local memory policy requested but CPUs are from NUMA nodes [1] while memory is on NUMA node 0 -``` - -## Performance Considerations - -### NUMA Locality -- **Local access**: Memory access within the same NUMA node (fastest) -- **Remote access**: Memory access across NUMA nodes (slower) -- **Cross-socket access**: Memory access across different sockets (slowest) - -### CPU Placement Strategies -1. **Compact placement**: Best for single-threaded or small multi-threaded workloads -2. **Spread placement**: Best for large multi-threaded workloads -3. **Local placement**: Best for memory-intensive workloads - -### Memory Allocation Strategies -1. **Local memory**: Fastest access, limited by NUMA node capacity -2. **Interleaved memory**: Higher bandwidth, higher latency -3. **Bound memory**: Predictable placement, may limit flexibility - -## Best Practices - -### 1. Workload Analysis -- **CPU-bound**: Use `compact` affinity with `local` memory policy -- **Memory-bound**: Use `local` affinity with `local` memory policy -- **I/O-bound**: Use `spread` affinity with `interleave` memory policy - -### 2. Resource Planning -- **Small instances**: Prefer single NUMA node allocation -- **Large instances**: Consider multi-NUMA node allocation -- **Critical instances**: Use `local` policies for best performance - -### 3. Topology Awareness -- **Understand your hardware**: Know your NUMA topology before configuration -- **Test configurations**: Validate performance with different topology settings -- **Monitor utilization**: Use system tools to verify optimal placement - -## Example Configurations - -### High-Performance Database -```dts -database { - resources { - cpus = <4 5 6 7 8 9 10 11>; // Single NUMA node - memory-base = <0x0 0x800000000>; - memory-bytes = <0x0 0x400000000>; // 16GB - numa-nodes = <0>; - cpu-affinity = "compact"; - memory-policy = "local"; - }; -}; -``` - -### Distributed Analytics -```dts -analytics { - resources { - cpus = <12 13 14 15 16 17 18 19 28 29 30 31>; // Cross-NUMA - memory-base = <0x0 0xA00000000>; - memory-bytes = <0x0 0x800000000>; // 32GB - numa-nodes = <0 1>; - cpu-affinity = "spread"; - memory-policy = "interleave"; - }; -}; -``` - -### Real-Time Processing -```dts -realtime { - resources { - cpus = <20 21 22 23>; // Single core, single NUMA node - memory-base = <0x0 0x1000000000>; - memory-bytes = <0x0 0x200000000>; // 8GB - numa-nodes = <1>; - cpu-affinity = "compact"; - memory-policy = "local"; - }; -}; -``` - -## Troubleshooting - -### Common Issues - -1. **NUMA node mismatch**: CPUs and memory on different NUMA nodes - - **Solution**: Use `local` affinity and memory policy - - **Check**: Verify NUMA node assignments in configuration - -2. **Performance degradation**: Remote memory access - - **Solution**: Ensure memory and CPUs are co-located - - **Check**: Use `numactl` to verify actual NUMA placement - -3. **Resource conflicts**: Multiple instances on same NUMA node - - **Solution**: Distribute instances across NUMA nodes - - **Check**: Monitor NUMA node utilization - -### Debugging Commands - -```bash -# Check NUMA topology -numactl --hardware - -# Check CPU topology -lscpu - -# Check memory allocation -numactl --show - -# Monitor NUMA statistics -cat /proc/vmstat | grep numa -``` - -## Future Enhancements - -### Planned Features -- **Dynamic topology discovery**: Automatic hardware topology detection -- **Performance profiling**: Integration with performance monitoring tools -- **Advanced policies**: More sophisticated allocation algorithms -- **Migration support**: Runtime topology-aware instance migration - -### Research Areas -- **Machine learning**: AI-driven topology optimization -- **Workload characterization**: Automatic policy selection based on workload patterns -- **Energy efficiency**: Power-aware topology management -- **Heterogeneous systems**: Support for different CPU types and memory hierarchies From 37f73e3aad1857f5f621accd55743ff92f649044 Mon Sep 17 00:00:00 2001 From: Cong Wang Date: Sun, 29 Nov 2026 16:45:42 -0800 Subject: [PATCH 2/3] create: Remove the topology placement options --cpu-affinity, --numa-nodes and --memory-policy came with the first kerf create and never did what their help says. They place CPUs by the NUMA nodes of a topology section in the baseline, and nothing in kerf writes that section, so every policy fell through to the same choice: a run of consecutive free CPU IDs, or else the first free ones. local was the exception, it could only fail. Remove the options and the three allocators, and keep that one choice for --cpu-count. An instance is no longer created with the properties the options left behind, of which cpu-affinity = "compact" was written for every instance because the option defaulted to it. The kernel does not read any of them. Signed-off-by: Cong Wang --- src/kerf/create/main.py | 210 ++-------------------------------------- 1 file changed, 7 insertions(+), 203 deletions(-) diff --git a/src/kerf/create/main.py b/src/kerf/create/main.py index 4cf111b..d3c7295 100644 --- a/src/kerf/create/main.py +++ b/src/kerf/create/main.py @@ -119,123 +119,15 @@ def _find_consecutive_cpus(cpu_list: List[int], count: int) -> Optional[List[int return None -def _allocate_compact( - tree, available: List[int], count: int, numa_nodes: Optional[List[int]] -) -> List[int]: - """Allocate CPUs with compact affinity policy.""" - if numa_nodes and tree.hardware.topology and tree.hardware.topology.numa_nodes: - for numa_node_id in numa_nodes: - numa_cpus = [ - cpu - for cpu in available - if tree.hardware.topology.get_numa_node_for_cpu(cpu) == numa_node_id - ] - if len(numa_cpus) >= count: - consecutive = _find_consecutive_cpus(numa_cpus, count) - if consecutive: - return sorted(consecutive) - return sorted(numa_cpus[:count]) - - consecutive = _find_consecutive_cpus(available, count) - if consecutive: - return consecutive - return available[:count] - - -def _allocate_spread( - tree, available: List[int], count: int, numa_nodes: Optional[List[int]] -) -> List[int]: - """Allocate CPUs with spread affinity policy.""" - if numa_nodes and tree.hardware.topology and tree.hardware.topology.numa_nodes: - numa_cpu_lists = {} - for numa_node_id in numa_nodes: - numa_cpus = [ - cpu - for cpu in available - if tree.hardware.topology.get_numa_node_for_cpu(cpu) == numa_node_id - ] - if numa_cpus: - numa_cpu_lists[numa_node_id] = sorted(numa_cpus) - - if not numa_cpu_lists: - raise ResourceError(f"No available {cpu_id_name()}s in specified NUMA nodes: {numa_nodes}") - - allocated = [] - numa_indices = {node_id: 0 for node_id in numa_cpu_lists} - - for i in range(count): - numa_idx = i % len(numa_cpu_lists) - numa_node_id = list(numa_cpu_lists.keys())[numa_idx] - cpu_list = numa_cpu_lists[numa_node_id] - - if numa_indices[numa_node_id] < len(cpu_list): - allocated.append(cpu_list[numa_indices[numa_node_id]]) - numa_indices[numa_node_id] += 1 - else: - for next_numa_id, next_cpu_list in numa_cpu_lists.items(): - if numa_indices[next_numa_id] < len(next_cpu_list): - allocated.append(next_cpu_list[numa_indices[next_numa_id]]) - numa_indices[next_numa_id] += 1 - break - - return sorted(allocated) - - if count == 1: - return [available[0]] - - step = (len(available) - 1) / (count - 1) if count > 1 else 1 - indices = [int(i * step) for i in range(count)] - return sorted([available[i] for i in indices]) - - -def _allocate_local( - tree, available: List[int], count: int, numa_nodes: Optional[List[int]] -) -> List[int]: - """Allocate CPUs with local affinity policy.""" - if not tree.hardware.topology or not tree.hardware.topology.numa_nodes: - raise ResourceError( - "CPU affinity 'local' requires NUMA topology information. " - "Use 'compact' or 'spread' instead, or specify NUMA topology in baseline." - ) - - if numa_nodes and len(numa_nodes) > 0: - numa_node_id = numa_nodes[0] - numa_cpus = [ - cpu - for cpu in available - if tree.hardware.topology.get_numa_node_for_cpu(cpu) == numa_node_id - ] - if len(numa_cpus) >= count: - return sorted(numa_cpus[:count]) - raise ResourceError( - f"Not enough {cpu_id_name()}s in NUMA node {numa_node_id}: " - f"requested {count}, but only {len(numa_cpus)} available" - ) - - for numa_node_id in tree.hardware.topology.numa_nodes: - numa_cpus = [ - cpu - for cpu in available - if tree.hardware.topology.get_numa_node_for_cpu(cpu) == numa_node_id - ] - if len(numa_cpus) >= count: - return sorted(numa_cpus[:count]) - - raise ResourceError(f"No single NUMA node has {count} available {cpu_id_name()}s for 'local' affinity") - - -def allocate_cpus_from_pool( - tree, count: int, cpu_affinity: str = "compact", numa_nodes: Optional[List[int]] = None -) -> List[int]: +def allocate_cpus_from_pool(tree, count: int) -> List[int]: """ - Allocate specified number of CPUs from available pool with topology awareness. + Allocate specified number of CPUs from available pool. + + Prefers a run of consecutive IDs, which are usually neighbours. Args: tree: GlobalDeviceTree to analyze count: Number of CPUs to allocate - cpu_affinity: CPU affinity policy - "compact", "spread", or "local" - numa_nodes: Preferred NUMA node IDs (optional). If specified, allocates - CPUs only from these NUMA nodes Returns: List of allocated CPU IDs (sorted) @@ -243,35 +135,15 @@ def allocate_cpus_from_pool( Raises: ResourceError: If not enough CPUs available """ - available = sorted(list(get_available_cpus(tree))) - - # Filter by NUMA nodes if specified - if numa_nodes and tree.hardware.topology and tree.hardware.topology.numa_nodes: - numa_filtered = [] - for cpu_id in available: - cpu_numa = tree.hardware.topology.get_numa_node_for_cpu(cpu_id) - if cpu_numa is not None and cpu_numa in numa_nodes: - numa_filtered.append(cpu_id) - available = numa_filtered + available = sorted(get_available_cpus(tree)) if len(available) < count: - if numa_nodes: - raise ResourceError( - f"Not enough {cpu_id_name()}s available in NUMA nodes {numa_nodes}: " - f"requested {count}, but only {len(available)} available" - ) raise ResourceError( f"Not enough {cpu_id_name()}s available: requested {count}, " f"but only {len(available)} available in pool" ) - if cpu_affinity == "compact": - return _allocate_compact(tree, available, count, numa_nodes) - if cpu_affinity == "spread": - return _allocate_spread(tree, available, count, numa_nodes) - if cpu_affinity == "local": - return _allocate_local(tree, available, count, numa_nodes) - raise ValueError(f"Unknown CPU affinity policy: {cpu_affinity}") + return _find_consecutive_cpus(available, count) or available[:count] def parse_memory_spec(memory_spec: str) -> int: @@ -396,24 +268,6 @@ def dump_overlay_for_debug( help="Auto-allocate specified number of CPUs from available pool. " "Mutually exclusive with --cpus", ) -@click.option( - "--cpu-affinity", - type=click.Choice(["compact", "spread", "local"]), - default="compact", - help="CPU affinity policy: compact (same NUMA node, consecutive), " - "spread (across NUMA nodes), or local (co-locate with memory)", -) -@click.option( - "--numa-nodes", - help='Preferred NUMA node IDs (comma-separated, e.g., "0" or "0,1"). ' - "CPUs allocated from these nodes only", -) -@click.option( - "--memory-policy", - type=click.Choice(["local", "interleave", "bind"]), - help="Memory allocation policy: local (same NUMA as CPUs), " - "interleave (across NUMA nodes), or bind (specific NUMA nodes)", -) @click.option( "--memory", "-m", help='Memory allocation (e.g., "2GB", "2048MB", or bytes)' ) @@ -447,9 +301,6 @@ def create( # pylint: disable=too-many-arguments,too-many-positional-arguments instance_id: Optional[int], cpus: Optional[str], cpu_count: Optional[int], - cpu_affinity: str, - numa_nodes: Optional[str], - memory_policy: Optional[str], memory: str, devices: Optional[str], input_path: Optional[str], @@ -489,14 +340,6 @@ def create( # pylint: disable=too-many-arguments,too-many-positional-arguments # Create instance with auto-allocated CPU count kerf create web-server --cpu-count=4 --memory=2GB - \b - # Create instance with topology-aware allocation (auto-allocated) - kerf create database --cpu-count=8 --memory=16GB --numa-nodes=0 --cpu-affinity=compact --memory-policy=local - - \b - # Create instance with spread affinity across multiple NUMA nodes (auto-allocated) - kerf create compute --cpu-count=16 --memory=32GB --numa-nodes=0,1 --cpu-affinity=spread --memory-policy=interleave - \b # Validate without applying kerf create web-server --cpu-count=4 --memory=2GB --dry-run @@ -524,8 +367,6 @@ def create( # pylint: disable=too-many-arguments,too-many-positional-arguments ("--cpu-count", cpu_count), ("--memory", memory), ("--devices", devices), - ("--numa-nodes", numa_nodes), - ("--memory-policy", memory_policy), ) if value is not None ] @@ -601,18 +442,6 @@ def create( # pylint: disable=too-many-arguments,too-many-positional-arguments # Parse device list device_list = parse_device_list(devices) - # Parse NUMA nodes (if specified) - numa_node_list = None - if numa_nodes: - try: - numa_node_list = [int(n.strip()) for n in numa_nodes.split(",") if n.strip()] - if not numa_node_list: - click.echo(f"Error: Invalid NUMA nodes specification '{numa_nodes}'", err=True) - sys.exit(2) - except ValueError as e: - click.echo(f"Error: Invalid NUMA nodes specification '{numa_nodes}': {e}", err=True) - sys.exit(2) - # Validate instance ID if specified if instance_id is not None: if instance_id < 1 or instance_id > 511: @@ -656,13 +485,7 @@ def create_instance_operation(current): # Allocate CPUs based on specification if is_count: - # Allocate CPUs automatically from available pool with topology awareness - cpu_list = allocate_cpus_from_pool( - modified, - cpu_spec_value, # cpu_spec_value is int (count) - cpu_affinity=cpu_affinity, - numa_nodes=numa_node_list, - ) + cpu_list = allocate_cpus_from_pool(modified, cpu_spec_value) else: cpu_list = expand_cpu_ranges(cpu_spec_value, known_cpu_ids(modified)) @@ -676,15 +499,11 @@ def create_instance_operation(current): raise ResourceError(f"Device '{ref}' is not in the pool") device_nodes.append(node) - # Create instance resources with topology settings resources = InstanceResources( cpus=cpu_list, memory_base=0, memory_bytes=memory_bytes, devices=device_nodes, - numa_nodes=numa_node_list, - cpu_affinity=cpu_affinity, - memory_policy=memory_policy, ) # Create instance @@ -715,15 +534,7 @@ def create_instance_operation(current): click.echo(f" CPUs: {cpu_spec_value} CPUs auto-allocated: {cpus_str}") else: click.echo(f" CPUs: {', '.join(map(format_cpu_id, instance.resources.cpus))}") - if instance.resources.cpu_affinity: - click.echo(f" CPU Affinity: {instance.resources.cpu_affinity}") - if instance.resources.numa_nodes: - click.echo( - f" NUMA Nodes: {', '.join(map(str, instance.resources.numa_nodes))}" - ) click.echo(f" Memory: {memory}") - if instance.resources.memory_policy: - click.echo(f" Memory Policy: {instance.resources.memory_policy}") if instance.resources.devices: click.echo(f" Devices: {', '.join(instance.resources.devices)}") click.echo(f" Instance ID: {instance.id}") @@ -755,14 +566,7 @@ def create_instance_operation(current): instance = manager.read_instance(name) click.echo(f" Instance ID: {instance.id}") click.echo(f" CPUs: {', '.join(map(format_cpu_id, instance.resources.cpus))}") - if instance.resources.cpu_affinity: - click.echo(f" CPU Affinity: {instance.resources.cpu_affinity}") - if instance.resources.numa_nodes: - numa_str = ", ".join(map(str, instance.resources.numa_nodes)) - click.echo(f" NUMA Nodes: {numa_str}") click.echo(f" Memory: {memory}") - if instance.resources.memory_policy: - click.echo(f" Memory Policy: {instance.resources.memory_policy}") if instance.resources.devices: click.echo(f" Devices: {', '.join(instance.resources.devices)}") except ResourceError as e: From e2ca52946d7d7284c8c37e258a88ba9dad1d1e7d Mon Sep 17 00:00:00 2001 From: Cong Wang Date: Sun, 29 Nov 2026 16:45:42 -0800 Subject: [PATCH 3/3] Remove the topology models that nothing fills in With the options of kerf create gone, the rest of the topology code has no way to run. An instance had numa_nodes, cpu_affinity and memory_policy, which only those options set. The overlay wrote them out, the update overlay pinned added CPUs and memory to the first of numa_nodes, and the validator checked them against the topology of the baseline in some 200 lines. The baseline had a topology section of NUMA nodes and a per-CPU record of socket, core and thread. The parser read the first from a section that kerf never writes, nothing set the second, and kerf show printed both when they were there. Remove all of it, with the tests that built these objects by hand. A baseline that carries a topology section is still parsed, the section is skipped. kerf show loses a verbose argument for the baseline, which only the per-CPU record used. The NUMA node of pool memory is not part of this: kerf init --memory=SIZE@N, the numa-node-id it writes and the lookup of a CPU's node in topology.py are unchanged. Signed-off-by: Cong Wang --- src/kerf/dtc/overlay.py | 28 +---- src/kerf/dtc/parser.py | 82 ------------- src/kerf/dtc/validator.py | 200 -------------------------------- src/kerf/models.py | 61 +--------- src/kerf/show/main.py | 28 +---- tests/test_models.py | 193 ------------------------------- tests/test_pool_overlay.py | 17 +-- tests/test_validator.py | 228 ------------------------------------- 8 files changed, 9 insertions(+), 828 deletions(-) diff --git a/src/kerf/dtc/overlay.py b/src/kerf/dtc/overlay.py index e618785..8953e4d 100644 --- a/src/kerf/dtc/overlay.py +++ b/src/kerf/dtc/overlay.py @@ -152,10 +152,6 @@ def generate_update_overlay(self, instance_name: str, old_instance, new_instance raise ResourceError(f"Growing instance '{instance_name}' needs a base for the new memory") memory_to_add = (memory_add_base, new_size - old_size) - numa_node = None - if new_instance.resources.numa_nodes: - numa_node = new_instance.resources.numa_nodes[0] - old_devices = set(old_instance.resources.devices) new_devices = set(new_instance.resources.devices) pci_ids = pci_ids or {} @@ -175,11 +171,11 @@ def generate_update_overlay(self, instance_name: str, old_instance, new_instance if memory_to_add: fdt_sw.begin_node("memory-add") - self._memory_item(fdt_sw, memory_to_add, numa_node) + self._memory_item(fdt_sw, memory_to_add) fdt_sw.end_node() self._cpu_op(fdt_sw, "cpu-remove", cpus_to_remove) - self._cpu_op(fdt_sw, "cpu-add", cpus_to_add, numa_node) + self._cpu_op(fdt_sw, "cpu-add", cpus_to_add) self._device_op(fdt_sw, "device-remove", devices_to_remove) self._device_op(fdt_sw, "device-add", devices_to_add) @@ -246,16 +242,14 @@ def generate_pool_overlay(self, diff: PoolDiff) -> bytes: dtb.pack() return dtb.as_bytearray() - def _memory_item(self, fdt_sw, region, numa_node=None, index=0): + def _memory_item(self, fdt_sw, region, index=0): """Write a memory@ item naming an existing range.""" base, size = region fdt_sw.begin_node(f"memory@{index}") fdt_sw.property("reg", struct.pack(">QQ", base, size)) - if numa_node is not None: - fdt_sw.property_u32("numa-node-id", numa_node) fdt_sw.end_node() - def _cpu_op(self, fdt_sw, operation, cpu_ids, numa_node=None): + def _cpu_op(self, fdt_sw, operation, cpu_ids): """Write a CPU operation node, or nothing when there are no CPUs.""" if not cpu_ids: return @@ -264,8 +258,6 @@ def _cpu_op(self, fdt_sw, operation, cpu_ids, numa_node=None): for cpu_id in cpu_ids: fdt_sw.begin_node(f"cpu@{cpu_id}") fdt_sw.property("reg", pack_cpu_id(cpu_id)) - if numa_node is not None: - fdt_sw.property_u32("numa-node-id", numa_node) fdt_sw.end_node() fdt_sw.end_node() @@ -326,18 +318,6 @@ def _create_overlay_dtb( fdt_sw.property_u64("memory-bytes", instance.resources.memory_bytes) - if instance.resources.numa_nodes: - numa_data = struct.pack( - ">" + "I" * len(instance.resources.numa_nodes), *instance.resources.numa_nodes - ) - fdt_sw.property("numa-nodes", numa_data) - - if instance.resources.cpu_affinity: - fdt_sw.property_string("cpu-affinity", instance.resources.cpu_affinity) - - if instance.resources.memory_policy: - fdt_sw.property_string("memory-policy", instance.resources.memory_policy) - fdt_sw.end_node() # End resources if instance.message_ring: diff --git a/src/kerf/dtc/parser.py b/src/kerf/dtc/parser.py index fb5ea81..b6944a7 100644 --- a/src/kerf/dtc/parser.py +++ b/src/kerf/dtc/parser.py @@ -33,10 +33,8 @@ Instance, InstanceResources, MemoryAllocation, - NUMANode, OverlayInstanceData, PoolMemoryRegion, - TopologySection, ) @@ -140,7 +138,6 @@ def _build_global_tree(self) -> GlobalDeviceTree: total_bytes=0, host_reserved_bytes=0, ), - topology=None, devices={} ) @@ -187,16 +184,12 @@ def _parse_hardware_inventory(self) -> HardwareInventory: except libfdt.FdtException as e: raise ParseError(f"Error parsing memory allocation: {e}") from e - # Parse topology section - topology = self._parse_topology(resources_node) - # Parse devices devices = self._parse_devices(resources_node) return HardwareInventory( cpus=cpus, memory=memory, - topology=topology, devices=devices ) @@ -735,81 +728,6 @@ def _parse_device_references(self) -> Dict[str, Dict]: return device_references - def _parse_topology(self, resources_node: int) -> Optional[TopologySection]: - """Parse topology section from resources node.""" - try: - topology_node = self.fdt.subnode_offset(resources_node, 'topology') - except libfdt.FdtException: - return None - - # Parse NUMA nodes from topology section - numa_nodes = self._parse_numa_nodes_from_topology(topology_node) - - return TopologySection(numa_nodes=numa_nodes) if numa_nodes else None - - def _parse_numa_nodes_from_topology(self, topology_node: int) -> Optional[Dict[int, NUMANode]]: - """Parse NUMA nodes from topology section.""" - try: - numa_nodes_node = self.fdt.subnode_offset(topology_node, 'numa-nodes') - except libfdt.FdtException: - return None - - nodes = {} - for offset in self._subnodes(numa_nodes_node): - node_name = self.fdt.get_name(offset) - if node_name.startswith('node@'): - node_id = int(node_name.split('@')[1]) - nodes[node_id] = self._parse_numa_node_info(offset, node_id) - - return nodes if nodes else None - - def _parse_numa_node_info(self, node_offset: int, node_id: int) -> NUMANode: - """Parse individual NUMA node information.""" - # Parse memory-base - memory_base = 0 - try: - memory_base = self.fdt.getprop(node_offset, 'memory-base').as_uint64() - except libfdt.FdtException: - pass - - # Parse memory-size - memory_size = 0 - try: - memory_size = self.fdt.getprop(node_offset, 'memory-size').as_uint64() - except libfdt.FdtException: - pass - - # Parse CPUs - cpus = [] - try: - cpus = self.fdt.getprop(node_offset, 'cpus').as_uint32_list() - except libfdt.FdtException: - pass - - # Parse distance matrix (optional) - distance_matrix = {} - try: - _ = self.fdt.getprop(node_offset, 'distance-matrix').as_uint32_list() - # Simple distance matrix parsing - would need more sophisticated logic for full matrix - except libfdt.FdtException: - pass - - # Parse memory type - memory_type = "dram" - try: - memory_type = self.fdt.getprop(node_offset, 'memory-type').as_str() - except libfdt.FdtException: - pass - - return NUMANode( - node_id=node_id, - memory_base=memory_base, - memory_size=memory_size, - cpus=cpus, - distance_matrix=distance_matrix, - memory_type=memory_type - ) - def dts_from_dtb(self, dtb_data: bytes) -> str: """Render a DTB as DTS text for reading; kerf does not parse it back.""" try: diff --git a/src/kerf/dtc/validator.py b/src/kerf/dtc/validator.py index c26c925..8f0d870 100644 --- a/src/kerf/dtc/validator.py +++ b/src/kerf/dtc/validator.py @@ -287,7 +287,6 @@ def _validate_instance_resources(self, instance, tree: GlobalDeviceTree): self._validate_cpu_allocation(instance, tree) self._validate_memory_allocation(instance, tree) self._validate_device_allocation(instance, tree) - self._validate_topology_constraints(instance, tree) def _validate_cpu_allocation(self, instance, tree: GlobalDeviceTree): """Validate CPU allocation for an instance.""" @@ -564,202 +563,3 @@ def _validate_resource_limits(self, usage: ResourceUsage, tree: GlobalDeviceTree self.warnings.append( f"Resource utilization: {unallocated_memory} bytes ({percentage:.1f}% of memory pool) remain unallocated" ) - - def _validate_topology_constraints(self, instance, tree: GlobalDeviceTree): - """Validate NUMA and CPU topology constraints for an instance.""" - resources = instance.resources - - if resources.numa_nodes and tree.hardware.topology and tree.hardware.topology.numa_nodes: - self._validate_numa_constraints(instance, tree) - if resources.cpu_affinity: - self._validate_cpu_affinity_constraints(instance, tree) - if resources.memory_policy: - self._validate_memory_policy_constraints(instance, tree) - - def _validate_numa_constraints(self, instance, tree: GlobalDeviceTree): - """Validate NUMA node constraints for an instance.""" - resources = instance.resources - topology = tree.hardware.topology - - if not topology or not topology.numa_nodes: - return - - for numa_node in resources.numa_nodes: - if numa_node not in topology.numa_nodes: - self.errors.append( - f"Instance {instance.name}: NUMA node {numa_node} does not exist in hardware topology" - ) - - if resources.numa_nodes: - for cpu in resources.cpus: - cpu_numa_node = topology.get_numa_node_for_cpu(cpu) - - if cpu_numa_node is not None and cpu_numa_node not in resources.numa_nodes: - self.warnings.append( - f"Instance {instance.name}: CPU {format_cpu_id(cpu)} is in NUMA node {cpu_numa_node}, " - f"but instance is configured for NUMA nodes {resources.numa_nodes}. " - f"This may cause performance issues due to remote memory access." - ) - - def _validate_cpu_affinity_constraints(self, instance, tree: GlobalDeviceTree): - """Validate CPU affinity constraints for an instance.""" - resources = instance.resources - - if resources.cpu_affinity == "compact": - self._validate_compact_affinity(instance, tree) - elif resources.cpu_affinity == "spread": - self._validate_spread_affinity(instance, tree) - elif resources.cpu_affinity == "local": - self._validate_local_affinity(instance, tree) - - def _validate_compact_affinity(self, instance, tree: GlobalDeviceTree): - """Validate compact CPU affinity.""" - resources = instance.resources - cpus = resources.cpus - - if not tree.hardware.topology or not tree.hardware.topology.numa_nodes: - return - - numa_nodes = set() - for cpu in cpus: - numa_node = tree.hardware.topology.get_numa_node_for_cpu(cpu) - if numa_node is not None: - numa_nodes.add(numa_node) - - if len(numa_nodes) > 1: - self.warnings.append( - f"Instance {instance.name}: Compact CPU affinity requested but CPUs span multiple NUMA nodes: {sorted(numa_nodes)}" - ) - - if tree.hardware.cpus.topology: - cores = set() - for cpu in cpus: - if cpu in tree.hardware.cpus.topology: - cores.add(tree.hardware.cpus.topology[cpu].core_id) - - if len(cores) > len(cpus) // 2: - self.warnings.append( - f"Instance {instance.name}: Compact CPU affinity may not be optimal - CPUs span {len(cores)} cores" - ) - - def _validate_spread_affinity(self, instance, tree: GlobalDeviceTree): - """Validate spread CPU affinity.""" - resources = instance.resources - cpus = resources.cpus - - if not tree.hardware.topology or not tree.hardware.topology.numa_nodes: - return - - numa_nodes = set() - for cpu in cpus: - numa_node = tree.hardware.topology.get_numa_node_for_cpu(cpu) - if numa_node is not None: - numa_nodes.add(numa_node) - - if len(numa_nodes) < 2: - self.warnings.append( - f"Instance {instance.name}: Spread CPU affinity requested but CPUs are from single NUMA node {list(numa_nodes)[0]}" - ) - - def _validate_local_affinity(self, instance, tree: GlobalDeviceTree): - """Validate local CPU affinity (CPUs and memory on same NUMA node).""" - resources = instance.resources - cpus = resources.cpus - - if not tree.hardware.topology or not tree.hardware.topology.numa_nodes: - return - - memory_numa_node = None - memory_base = resources.memory_base - - for node_id, node in tree.hardware.topology.numa_nodes.items(): - if node.memory_base <= memory_base < node.memory_base + node.memory_size: - memory_numa_node = node_id - break - - if memory_numa_node is None: - self.warnings.append( - f"Instance {instance.name}: Could not determine NUMA node for memory allocation at {hex(memory_base)}" - ) - return - - cpu_numa_nodes = set() - for cpu in cpus: - numa_node = tree.hardware.topology.get_numa_node_for_cpu(cpu) - if numa_node is not None: - cpu_numa_nodes.add(numa_node) - - if memory_numa_node not in cpu_numa_nodes: - self.warnings.append( - f"Instance {instance.name}: Local affinity requested but CPUs are from NUMA nodes {sorted(cpu_numa_nodes)} " - f"while memory is on NUMA node {memory_numa_node}" - ) - - def _validate_memory_policy_constraints(self, instance, tree: GlobalDeviceTree): - """Validate memory policy constraints for an instance.""" - resources = instance.resources - - if resources.memory_policy == "local": - self._validate_local_memory_policy(instance, tree) - elif resources.memory_policy == "interleave": - self._validate_interleave_memory_policy(instance, tree) - elif resources.memory_policy == "bind": - self._validate_bind_memory_policy(instance, tree) - - def _validate_local_memory_policy(self, instance, tree: GlobalDeviceTree): - """Validate local memory policy.""" - resources = instance.resources - - if not tree.hardware.topology or not tree.hardware.topology.numa_nodes: - return - - memory_numa_node = None - memory_base = resources.memory_base - - for node_id, node in tree.hardware.topology.numa_nodes.items(): - if node.memory_base <= memory_base < node.memory_base + node.memory_size: - memory_numa_node = node_id - break - - if memory_numa_node is None: - self.warnings.append( - f"Instance {instance.name}: Local memory policy requested but memory allocation " - f"at {hex(memory_base)} is not within any NUMA node memory range" - ) - return - - cpu_numa_nodes = set() - for cpu in resources.cpus: - numa_node = tree.hardware.topology.get_numa_node_for_cpu(cpu) - if numa_node is not None: - cpu_numa_nodes.add(numa_node) - - if memory_numa_node not in cpu_numa_nodes: - self.warnings.append( - f"Instance {instance.name}: Local memory policy requested but CPUs are from NUMA nodes " - f"{sorted(cpu_numa_nodes)} while memory is on NUMA node {memory_numa_node}" - ) - - def _validate_interleave_memory_policy(self, instance, tree: GlobalDeviceTree): - """Validate interleave memory policy.""" - # For interleave policy, we would typically check if memory is distributed - # across multiple NUMA nodes, but this is complex to validate without - # knowing the actual memory allocation implementation - _ = instance, tree # Placeholder for future validation - - def _validate_bind_memory_policy(self, instance, tree: GlobalDeviceTree): - """Validate bind memory policy.""" - resources = instance.resources - - if not resources.numa_nodes: - self.warnings.append( - f"Instance {instance.name}: Bind memory policy requested but no NUMA nodes specified" - ) - return - - if tree.hardware.topology and tree.hardware.topology.numa_nodes: - for numa_node in resources.numa_nodes: - if numa_node not in tree.hardware.topology.numa_nodes: - self.errors.append( - f"Instance {instance.name}: Bind memory policy references non-existent NUMA node {numa_node}" - ) diff --git a/src/kerf/models.py b/src/kerf/models.py index d751555..08e3870 100644 --- a/src/kerf/models.py +++ b/src/kerf/models.py @@ -18,7 +18,7 @@ from dataclasses import dataclass, field from enum import Enum -from typing import List, Dict, Optional, Set, Tuple +from typing import List, Dict, Optional, Set from .devices import normalize_pci_id @@ -64,31 +64,6 @@ class InstanceConfig: enable_numa: Optional[bool] = None -@dataclass -class CPUTopology: - """CPU topology information.""" - - cpu_id: int - numa_node: int - core_id: int - thread_id: int - socket_id: int - cache_levels: List[int] # Cache sizes at each level - flags: List[str] # CPU flags like "smt", "ht", etc. - - -@dataclass -class NUMANode: - """NUMA node information.""" - - node_id: int - memory_base: int - memory_size: int - cpus: List[int] - distance_matrix: Dict[int, int] # Distance to other NUMA nodes - memory_type: str # "dram", "hbm", "cxl", etc. - - @dataclass class CPUAllocation: """CPU allocation information.""" @@ -96,7 +71,6 @@ class CPUAllocation: total: int host_reserved: List[int] available: List[int] # Pool membership: every CPU in the pool, lent or free - topology: Optional[Dict[int, CPUTopology]] = None # CPU ID -> topology info available_free: Optional[List[int]] = None # Pool members not lent to an instance # Pool members the host never booted: there without being asked for, for good unclaimed: List[int] = field(default_factory=list) @@ -178,9 +152,6 @@ class InstanceResources: memory_base: int memory_bytes: int devices: List[str] # List of device references - numa_nodes: Optional[List[int]] = None # Preferred NUMA nodes - cpu_affinity: Optional[str] = None # "compact", "spread", "local" - memory_policy: Optional[str] = None # "local", "interleave", "bind" @dataclass @@ -194,42 +165,12 @@ class Instance: message_ring: bool = True # False makes a static partition no kernel can message -@dataclass -class TopologySection: - """Generic topology section containing all topology types.""" - - numa_nodes: Optional[Dict[int, NUMANode]] = None # NUMA node ID -> node info - - def get_cpus_in_numa_node(self, numa_node: int) -> List[int]: - """Get all CPUs in a specific NUMA node.""" - if not self.numa_nodes or numa_node not in self.numa_nodes: - return [] - return self.numa_nodes[numa_node].cpus - - def get_numa_node_for_cpu(self, cpu_id: int) -> Optional[int]: - """Get NUMA node ID for a specific CPU.""" - if not self.numa_nodes: - return None - for node_id, node in self.numa_nodes.items(): - if cpu_id in node.cpus: - return node_id - return None - - def get_memory_region_for_numa_node(self, numa_node: int) -> Optional[Tuple[int, int]]: - """Get memory region (base, size) for a specific NUMA node.""" - if not self.numa_nodes or numa_node not in self.numa_nodes: - return None - node = self.numa_nodes[numa_node] - return (node.memory_base, node.memory_size) - - @dataclass class HardwareInventory: """Complete hardware inventory.""" cpus: CPUAllocation memory: MemoryAllocation - topology: Optional[TopologySection] = None devices: Dict[str, DeviceInfo] = None def find_device(self, ref: str) -> Optional[str]: diff --git a/src/kerf/show/main.py b/src/kerf/show/main.py index 90f101f..540cca9 100644 --- a/src/kerf/show/main.py +++ b/src/kerf/show/main.py @@ -36,7 +36,7 @@ from ..models import DeviceInfo, GlobalDeviceTree from ..pool_diff import ANY_NODE from ..resources import get_pool_allocated_bytes -from ..topology import format_cpu_id, format_cpu_ids +from ..topology import format_cpu_ids from ..utils import get_instance_id_from_name, get_instance_status, resolve_instance @@ -148,13 +148,12 @@ def read_loaded_image(instance_id: int) -> Optional[Dict[str, str]]: os.close(fd) -def display_baseline_info(tree: GlobalDeviceTree, verbose: bool = False): +def display_baseline_info(tree: GlobalDeviceTree): """ Display formatted baseline hardware information. Args: tree: GlobalDeviceTree containing hardware resources - verbose: Whether to show verbose information """ click.echo(f"\n{'=' * 80}") click.echo("Baseline Hardware Resources") @@ -192,13 +191,6 @@ def display_baseline_info(tree: GlobalDeviceTree, verbose: bool = False): click.echo(f" Kind {kind}: {len(of_kind)} cpus: {format_cpu_ids(of_kind)}" + (" (the host's)" if kind == 0 else "")) - if verbose and hardware.cpus.topology: - click.echo("\n Topology:") - for cpu_id, topo in sorted(hardware.cpus.topology.items()): - click.echo( - f" CPU {format_cpu_id(cpu_id)}: NUMA {topo.numa_node}, Socket {topo.socket_id}, Core {topo.core_id}, Thread {topo.thread_id}" - ) - # Memory Information click.echo("\n Memory:") # total_bytes/host_reserved_bytes are 0 when the tree only carries pool @@ -237,20 +229,6 @@ def display_baseline_info(tree: GlobalDeviceTree, verbose: bool = False): else: click.echo(" Pool Usage: unknown, /proc/iomem shows addresses only to root") - # NUMA Topology - if hardware.topology and hardware.topology.numa_nodes: - click.echo("\n NUMA Topology:") - for node_id, numa_node in sorted(hardware.topology.numa_nodes.items()): - mem_gb = numa_node.memory_size / (1024**3) - click.echo(f" Node {node_id}:") - click.echo(f" Memory: {mem_gb:.2f} GB (base: 0x{numa_node.memory_base:x})") - click.echo(f" CPUs: {format_cpu_ids(numa_node.cpus)}") - click.echo(f" Type: {numa_node.memory_type}") - if verbose and numa_node.distance_matrix: - click.echo(" Distance:") - for target_node, distance in sorted(numa_node.distance_matrix.items()): - click.echo(f" -> Node {target_node}: {distance}") - _display_devices(hardware.devices) @@ -488,7 +466,7 @@ def show(name: Optional[str], verbose: bool): if verbose: click.echo(f"\nWarning: Could not read baseline: {e}", err=True) else: - display_baseline_info(tree, verbose) + display_baseline_info(tree) if not instance_names: click.echo("\n" + "=" * 80) diff --git a/tests/test_models.py b/tests/test_models.py index 5d101b7..8d975dc 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -136,196 +136,3 @@ def test_instance_creation(self): assert instance.name == "web-server" assert instance.id == 1 assert instance.resources == resources - - def test_instance_with_numa_nodes(self): - """Test instance with NUMA node constraints.""" - resources = InstanceResources( - cpus=[4, 5, 6, 7], - memory_base=0x80000000, - memory_bytes=2 * 1024**3, - devices=[], - numa_nodes=[0, 1], - ) - - instance = Instance(name="numa-instance", id=1, resources=resources) - - assert instance.resources.numa_nodes == [0, 1] - - def test_instance_with_cpu_affinity(self): - """Test instance with CPU affinity.""" - resources = InstanceResources( - cpus=[4, 5, 6, 7], - memory_base=0x80000000, - memory_bytes=2 * 1024**3, - devices=[], - cpu_affinity="compact", - ) - - instance = Instance(name="affinity-instance", id=1, resources=resources) - - assert instance.resources.cpu_affinity == "compact" - - def test_instance_with_memory_policy(self): - """Test instance with memory policy.""" - resources = InstanceResources( - cpus=[4, 5, 6, 7], - memory_base=0x80000000, - memory_bytes=2 * 1024**3, - devices=[], - memory_policy="local", - ) - - instance = Instance(name="policy-instance", id=1, resources=resources) - - assert instance.resources.memory_policy == "local" - - -class TestTopology: - """Test topology models.""" - - def test_numa_node_creation(self): - """Test NUMA node creation.""" - from kerf.models import NUMANode - - node = NUMANode( - node_id=0, - memory_base=0x80000000, - memory_size=8 * 1024**3, - cpus=[0, 1, 2, 3], - distance_matrix={0: 10, 1: 20}, - memory_type="dram", - ) - - assert node.node_id == 0 - assert node.memory_base == 0x80000000 - assert node.memory_size == 8 * 1024**3 - assert node.cpus == [0, 1, 2, 3] - assert node.distance_matrix == {0: 10, 1: 20} - assert node.memory_type == "dram" - - def test_topology_section_get_cpus_in_numa_node(self): - """Test getting CPUs in NUMA node.""" - from kerf.models import TopologySection, NUMANode - - nodes = { - 0: NUMANode( - node_id=0, - memory_base=0x80000000, - memory_size=8 * 1024**3, - cpus=[0, 1, 2, 3], - distance_matrix={}, - memory_type="dram", - ), - 1: NUMANode( - node_id=1, - memory_base=0x100000000, - memory_size=8 * 1024**3, - cpus=[4, 5, 6, 7], - distance_matrix={}, - memory_type="dram", - ), - } - - topology = TopologySection(numa_nodes=nodes) - - cpus = topology.get_cpus_in_numa_node(0) - assert cpus == [0, 1, 2, 3] - - cpus = topology.get_cpus_in_numa_node(1) - assert cpus == [4, 5, 6, 7] - - cpus = topology.get_cpus_in_numa_node(999) - assert cpus == [] - - def test_topology_section_get_numa_node_for_cpu(self): - """Test getting NUMA node for CPU.""" - from kerf.models import TopologySection, NUMANode - - nodes = { - 0: NUMANode( - node_id=0, - memory_base=0x80000000, - memory_size=8 * 1024**3, - cpus=[0, 1, 2, 3], - distance_matrix={}, - memory_type="dram", - ), - 1: NUMANode( - node_id=1, - memory_base=0x100000000, - memory_size=8 * 1024**3, - cpus=[4, 5, 6, 7], - distance_matrix={}, - memory_type="dram", - ), - } - - topology = TopologySection(numa_nodes=nodes) - - assert topology.get_numa_node_for_cpu(0) == 0 - assert topology.get_numa_node_for_cpu(5) == 1 - assert topology.get_numa_node_for_cpu(999) is None - - def test_topology_section_get_memory_region_for_numa_node(self): - """Test getting memory region for NUMA node.""" - from kerf.models import TopologySection, NUMANode - - nodes = { - 0: NUMANode( - node_id=0, - memory_base=0x80000000, - memory_size=8 * 1024**3, - cpus=[0, 1, 2, 3], - distance_matrix={}, - memory_type="dram", - ) - } - - topology = TopologySection(numa_nodes=nodes) - - region = topology.get_memory_region_for_numa_node(0) - assert region == (0x80000000, 8 * 1024**3) - - region = topology.get_memory_region_for_numa_node(999) - assert region is None - - -class TestWorkloadType: - """Test workload type enum.""" - - def test_workload_types(self): - """Test workload type values.""" - from kerf.models import WorkloadType - - assert WorkloadType.WEB_SERVER.value == "web-server" - assert WorkloadType.DATABASE_OLTP.value == "database-oltp" - assert WorkloadType.COMPUTE.value == "compute" - assert WorkloadType.STORAGE.value == "storage" - assert WorkloadType.NETWORK.value == "network" - - -class TestInstanceState: - """Test instance state enum.""" - - def test_instance_states(self): - """Test instance state values.""" - from kerf.models import InstanceState - - assert InstanceState.EMPTY.value == "empty" - assert InstanceState.READY.value == "ready" - assert InstanceState.LOADED.value == "loaded" - assert InstanceState.ACTIVE.value == "active" - assert InstanceState.FAILED.value == "failed" - - -class TestFindDevice: - """Pool devices are named by node name or PCI address.""" - - def test_by_node_name(self, sample_hardware): - assert sample_hardware.find_device("eth0") == "eth0" - - def test_by_pci_address(self, sample_hardware): - assert sample_hardware.find_device("0000:01:00.0") == "eth0" - - def test_unknown(self, sample_hardware): - assert sample_hardware.find_device("0000:09:00.0") is None diff --git a/tests/test_pool_overlay.py b/tests/test_pool_overlay.py index a00a733..19c8aec 100644 --- a/tests/test_pool_overlay.py +++ b/tests/test_pool_overlay.py @@ -44,11 +44,10 @@ def _walk(fdt, offset=0): child = fdt.next_subnode(child, quiet=[libfdt.FDT_ERR_NOTFOUND]) -def _grown(instance, cpus, memory_bytes, numa_nodes=None): +def _grown(instance, cpus, memory_bytes): new = copy.deepcopy(instance) new.resources.cpus = cpus new.resources.memory_bytes = memory_bytes - new.resources.numa_nodes = numa_nodes return new @@ -110,20 +109,6 @@ def test_update_overlay_targets_the_instance_path(sample_instances): assert fdt.subnode_offset(add, "region@0", quiet=[libfdt.FDT_ERR_NOTFOUND]) == MISSING -def test_update_overlay_pins_new_resources_to_the_instance_node(sample_instances): - old = sample_instances["database"] - new = _grown(old, old.resources.cpus + [16], old.resources.memory_bytes + GB, numa_nodes=[1]) - fdt, ov = _ov(OverlayGenerator().generate_update_overlay("database", old, new, - memory_add_base=0x140000000)) - - cpu = fdt.subnode_offset(fdt.subnode_offset(ov, "cpu-add"), "cpu@16") - assert fdt.getprop(cpu, "numa-node-id").as_uint32() == 1 - assert fdt.getprop(cpu, "numa-node", quiet=[libfdt.FDT_ERR_NOTFOUND]) == MISSING - - mem = fdt.subnode_offset(fdt.subnode_offset(ov, "memory-add"), "memory@0") - assert fdt.getprop(mem, "numa-node-id").as_uint32() == 1 - - def test_update_overlay_grow_needs_a_base(sample_instances): old = sample_instances["database"] new = _grown(old, old.resources.cpus, old.resources.memory_bytes + GB) diff --git a/tests/test_validator.py b/tests/test_validator.py index 031bb51..6e11cbc 100644 --- a/tests/test_validator.py +++ b/tests/test_validator.py @@ -163,234 +163,6 @@ def test_duplicate_instance_names(self, sample_hardware): assert any("Duplicate instance name" in error for error in result.errors) -class TestNUMAValidation: - """Test NUMA topology validation.""" - - def test_validate_numa_constraints(self, sample_hardware): - """Test NUMA node constraint validation.""" - from kerf.models import ( - Instance, - InstanceResources, - GlobalDeviceTree, - TopologySection, - NUMANode, - ) - - # Add topology to hardware - numa_nodes = { - 0: NUMANode( - node_id=0, - memory_base=0x80000000, - memory_size=8 * 1024**3, - cpus=[0, 1, 2, 3, 4, 5, 6, 7], - distance_matrix={0: 10, 1: 20}, - memory_type="dram", - ), - 1: NUMANode( - node_id=1, - memory_base=0x100000000, - memory_size=8 * 1024**3, - cpus=[8, 9, 10, 11, 12, 13, 14, 15], - distance_matrix={0: 20, 1: 10}, - memory_type="dram", - ), - } - - sample_hardware.topology = TopologySection(numa_nodes=numa_nodes) - - # Create instance with invalid NUMA node - instances = { - "app1": Instance( - name="app1", - id=1, - resources=InstanceResources( - cpus=[4, 5, 6, 7], - memory_base=0x80000000, - memory_bytes=2 * 1024**3, - devices=[], - numa_nodes=[999], # Invalid NUMA node - ), - ) - } - - tree = GlobalDeviceTree(hardware=sample_hardware, instances=instances, device_references={}) - - validator = MultikernelValidator() - result = validator.validate(tree) - - assert not result.is_valid - assert any("NUMA node" in error and "does not exist" in error for error in result.errors) - - def test_validate_cpu_numa_mismatch_warning(self, sample_hardware): - """Test warning for CPU/NUMA node mismatch.""" - from kerf.models import ( - Instance, - InstanceResources, - GlobalDeviceTree, - TopologySection, - NUMANode, - ) - - # Add topology to hardware - numa_nodes = { - 0: NUMANode( - node_id=0, - memory_base=0x80000000, - memory_size=8 * 1024**3, - cpus=[0, 1, 2, 3, 4, 5, 6, 7], - distance_matrix={}, - memory_type="dram", - ), - 1: NUMANode( - node_id=1, - memory_base=0x100000000, - memory_size=8 * 1024**3, - cpus=[8, 9, 10, 11, 12, 13, 14, 15], - distance_matrix={}, - memory_type="dram", - ), - } - - sample_hardware.topology = TopologySection(numa_nodes=numa_nodes) - - # Create instance with CPU from NUMA 0 but requesting NUMA 1 - instances = { - "app1": Instance( - name="app1", - id=1, - resources=InstanceResources( - cpus=[4, 5, 6, 7], # NUMA 0 CPUs - memory_base=0x100000000, # NUMA 1 memory - memory_bytes=2 * 1024**3, - devices=[], - numa_nodes=[1], # Requesting NUMA 1 - ), - ) - } - - tree = GlobalDeviceTree(hardware=sample_hardware, instances=instances, device_references={}) - - validator = MultikernelValidator() - result = validator.validate(tree) - - # Should have warnings about NUMA mismatch - assert any("NUMA" in warning for warning in result.warnings) - - def test_validate_compact_affinity(self, sample_hardware): - """Test compact CPU affinity validation.""" - from kerf.models import ( - Instance, - InstanceResources, - GlobalDeviceTree, - TopologySection, - NUMANode, - ) - - # Add topology to hardware - numa_nodes = { - 0: NUMANode( - node_id=0, - memory_base=0x80000000, - memory_size=8 * 1024**3, - cpus=[0, 1, 2, 3, 4, 5, 6, 7], - distance_matrix={}, - memory_type="dram", - ), - 1: NUMANode( - node_id=1, - memory_base=0x100000000, - memory_size=8 * 1024**3, - cpus=[8, 9, 10, 11, 12, 13, 14, 15], - distance_matrix={}, - memory_type="dram", - ), - } - - sample_hardware.topology = TopologySection(numa_nodes=numa_nodes) - - # Create instance with compact affinity but CPUs span multiple NUMA nodes - instances = { - "app1": Instance( - name="app1", - id=1, - resources=InstanceResources( - cpus=[4, 5, 8, 9], # CPUs from both NUMA 0 and 1 - memory_base=0x80000000, - memory_bytes=2 * 1024**3, - devices=[], - cpu_affinity="compact", - ), - ) - } - - tree = GlobalDeviceTree(hardware=sample_hardware, instances=instances, device_references={}) - - validator = MultikernelValidator() - result = validator.validate(tree) - - # Should have warnings about compact affinity - assert any( - "Compact" in warning and "multiple NUMA nodes" in warning for warning in result.warnings - ) - - def test_validate_spread_affinity(self, sample_hardware): - """Test spread CPU affinity validation.""" - from kerf.models import ( - Instance, - InstanceResources, - GlobalDeviceTree, - TopologySection, - NUMANode, - ) - - # Add topology to hardware - numa_nodes = { - 0: NUMANode( - node_id=0, - memory_base=0x80000000, - memory_size=8 * 1024**3, - cpus=[0, 1, 2, 3, 4, 5, 6, 7], - distance_matrix={}, - memory_type="dram", - ), - 1: NUMANode( - node_id=1, - memory_base=0x100000000, - memory_size=8 * 1024**3, - cpus=[8, 9, 10, 11, 12, 13, 14, 15], - distance_matrix={}, - memory_type="dram", - ), - } - - sample_hardware.topology = TopologySection(numa_nodes=numa_nodes) - - # Create instance with spread affinity but CPUs from single NUMA node - instances = { - "app1": Instance( - name="app1", - id=1, - resources=InstanceResources( - cpus=[4, 5, 6, 7], # All from NUMA 0 - memory_base=0x80000000, - memory_bytes=2 * 1024**3, - devices=[], - cpu_affinity="spread", - ), - ) - } - - tree = GlobalDeviceTree(hardware=sample_hardware, instances=instances, device_references={}) - - validator = MultikernelValidator() - result = validator.validate(tree) - - # Should have warnings about spread affinity - assert any( - "Spread" in warning and "single NUMA node" in warning for warning in result.warnings - ) - - class TestPoolChunks: """Test the pool read-back against /proc/iomem."""