From acd2f2e4503ca8eed46d0a4e39e527070709b4fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=98yvind=20Harboe?= Date: Fri, 13 Mar 2026 08:54:00 +0100 Subject: [PATCH 1/4] retire deltaDebug.py in favor of whittle.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove deltaDebug.py, test_deltaDebug.py, and their Bazel targets. Rename remaining deltaDebug_ prefixes in whittle.py to whittle_. Co-Authored-By: Claude Opus 4.6 Signed-off-by: Øyvind Harboe --- etc/BUILD | 14 -- etc/deltaDebug.py | 449 ----------------------------------------- etc/test_deltaDebug.py | 214 -------------------- etc/test_whittle.py | 4 +- etc/whittle.py | 17 +- 5 files changed, 10 insertions(+), 688 deletions(-) delete mode 100644 etc/deltaDebug.py delete mode 100644 etc/test_deltaDebug.py diff --git a/etc/BUILD b/etc/BUILD index c5d4b744661..396a9a8dd40 100644 --- a/etc/BUILD +++ b/etc/BUILD @@ -23,24 +23,10 @@ py_binary( test_suite( name = "all_tests", tests = [ - ":test_delta_debug", ":test_whittle", ], ) -py_library( - name = "delta_debug_lib", - srcs = ["deltaDebug.py"], - imports = ["."], -) - -py_test( - name = "test_delta_debug", - srcs = ["test_deltaDebug.py"], - main = "test_deltaDebug.py", - deps = [":delta_debug_lib"], -) - py_test( name = "test_whittle", srcs = ["test_whittle.py"], diff --git a/etc/deltaDebug.py b/etc/deltaDebug.py deleted file mode 100644 index 3a752195d4f..00000000000 --- a/etc/deltaDebug.py +++ /dev/null @@ -1,449 +0,0 @@ -################################ -# You need to provide the script with 3 main arguments -# --base_db_path -# --error_string -# --step -# You also have 1 additional argument -# --persistence -# --use_stdout -# --dump_def - -# EXAMPLE COMMAND: -# Assuming running in a directory with the following files in: -# deltaDebug.py base.odb step.sh -# openroad -python deltaDebug.py \ -# --base_db_path base.odb \ -# --error_string \ -# --step './step.sh' \ -# --persistence 5 --use_stdout --dump_def - -# N.B: step.sh shall read base.odb (or base.def in case the flag dump_def = 1) -# and operate on it where the script manipulates base.odb between steps to -# reduce its size. -################################ - -import odb -from openroad import Design -import os -import sys -import signal -import subprocess -import argparse -import shutil -import select -import time -from math import ceil -import errno -import enum - -persistence_range = [1, 2, 3, 4, 5, 6] -cut_multiple = range(1, 128) - -parser = argparse.ArgumentParser("Arguments for delta debugging") -parser.add_argument( - "--base_db_path", type=str, help="Path to the db file to perform the step on" -) -parser.add_argument( - "--error_string", - type=str, - help="The output that indicates target error has occurred", -) -parser.add_argument( - "--step", type=str, help="Command used to perform step on the input odb file" -) -parser.add_argument( - "--timeout", - type=int, - default=None, - help="Specify initial timeout in seconds, default is to measure it", -) -parser.add_argument( - "--multiplier", - type=int, - default=cut_multiple[0], - choices=cut_multiple, - help="Multiply number of cuts with this number", -) -parser.add_argument( - "--persistence", - type=int, - default=persistence_range[0], - choices=persistence_range, - help="Indicates maximum input fragmentation; " - "fragments = 2^persistence; value in " + ", ".join(map(str, persistence_range)), -) -parser.add_argument( - "--use_stdout", - action="store_true", - help="Enables reading the error string from standard output", -) -parser.add_argument( - "--exit_early_on_error", - action="store_true", - help=( - "Exit early on unrelated errors to speed things up, " - + "but risks exiting on false negatives." - ), -) -parser.add_argument( - "--dump_def", - action="store_true", - help="Determines whether to dumb def at each step in addition to the odb", -) - - -class cutLevel(enum.Enum): - Nets = 0 - Insts = 1 - - -class deltaDebugger: - def __init__(self, opt): - if not os.path.exists(opt.base_db_path): - raise FileNotFoundError( - errno.ENOENT, os.strerror(errno.ENOENT), opt.base_db_path - ) - - base_db_directory = os.path.dirname(opt.base_db_path) - base_db_name = os.path.basename(opt.base_db_path) - self.base_db_file = opt.base_db_path - - self.error_string = opt.error_string - self.use_stdout = opt.use_stdout - self.exit_early_on_error = opt.exit_early_on_error - self.step_count = 1 - - # Setting persistence for the run - self.persistence = opt.persistence - - self.multiplier = opt.multiplier - self.timeout = opt.timeout - - # Temporary file names to hold the original base_db file across the run - self.original_base_db_file = os.path.join( - base_db_directory, f"deltaDebug_base_original_{base_db_name}" - ) - - # Temporary file used to hold current base_db to ensure its integrity across cuts - self.temp_base_db_file = os.path.join( - base_db_directory, f"deltaDebug_base_temp_{base_db_name}" - ) - - # The name of the result file after running deltaDebug - self.deltaDebug_result_base_file = os.path.join( - base_db_directory, f"deltaDebug_base_result_{base_db_name}" - ) - - # This determines whether design def shall be dumped or not - self.dump_def = opt.dump_def - if self.dump_def != 0: - self.base_def_file = self.base_db_file[:-3] + "def" - - # A variable to hold the base_db - self.base_db = None - - # Debugging level - # cutLevel.Insts starts with inst then nets, - # cutLevel.Nets cuts nets only. - self.cut_level = cutLevel.Insts - - # step command - self.step = opt.step - - def debug(self): - # copy original base db file to avoid overwriting it - print("Backing up original base file.") - shutil.copy(self.base_db_file, self.original_base_db_file) - - # Rename the base db file to a temp name to keep it from - # overwriting across the two steps cut - os.rename(self.base_db_file, self.temp_base_db_file) - - if self.timeout is None: - # timeout used to measure the time the original input takes - # to reach an error to use as standard timeout for different - # cuts. - self.timeout = 1e6 # Timeout in seconds - - # Perform a step with no cuts to measure timeout - print( - "Performing a step with the original " - + "input file to calculate timeout." - ) - error, _ = self.perform_step() - if error is None: - print("No error found in the original input file.") - sys.exit(1) - - for self.cut_level in (cutLevel.Insts, cutLevel.Nets): - while True: - err = None - self.n = 2 # Initial Number of cuts - - cuts = None - - while self.n <= (2**self.persistence): - error_in_range = None - j = 0 - while j == 0 or j < cuts: - current_err, cuts = self.perform_step(cut_index=j) - self.step_count += 1 - if current_err is not None: - # Found the target error with the cut DB - # - # This is a suitable level of detail to look - # for more errors, complete this level of detail. - err = current_err - error_in_range = current_err - self.prepare_new_step() - j += 1 - - if error_in_range is None: - # Increase the granularity of the cut in case target - # error not found - self.n *= 2 - elif self.n >= 8: - # Found errors, decrease granularity - self.n = int(self.n / 2) - else: - break - - if err is None or cuts == 0: - break - - # Delete unused master-cells from design - self.remove_unused_masters() - - # Change deltaDebug resultant base_db - # file name to a representative name - if os.path.exists(self.temp_base_db_file): - os.rename(self.temp_base_db_file, self.deltaDebug_result_base_file) - - # Restoring the original base_db file - if os.path.exists(self.original_base_db_file): - os.rename(self.original_base_db_file, self.base_db_file) - - print("___________________________________") - print(f"Resultant file is {self.deltaDebug_result_base_file}") - print("Delta Debugging Done!") - - # A function that do a cut in the db, writes the base db to disk - # and calls the step function, then returns the stderr of the step. - def perform_step(self, cut_index=-1): - # read base db in memory - self.base_db = Design.createDetachedDb() - self.base_db = odb.read_db(self.base_db, self.temp_base_db_file) - - # Cut the block with the given step index. - # if cut index of -1 is provided it means - # that no cut will be made. - if cut_index != -1: - self.cut_block(index=cut_index) - - # Write DB - odb.write_db(self.base_db, self.base_db_file) - if self.dump_def != 0: - print("Writing def file") - odb.write_def(self.base_db.getChip().getBlock(), self.base_def_file) - - cuts = self.get_cuts() if cut_index != -1 else None - - # Destroy the DB in memory to avoid being out-of-memory when - # the step code is running - if self.base_db is not None: - self.base_db.destroy(self.base_db) - self.base_db = None - - # Perform step, and check the error code - start_time = time.time() - error_string = self.run_command(self.step) - end_time = time.time() - - # Handling timeout so as not to run the code for time - # that is more than the original buggy code or a - # buggy cut. - if error_string is not None: - self.timeout = max(120, 1.2 * (end_time - start_time)) - print(f"Error Code found: {error_string}") - - return error_string, cuts - - def run_command(self, command): - poll_obj = select.poll() - if self.use_stdout == 0: - process = subprocess.Popen( - command, - shell=True, - stdout=subprocess.DEVNULL, - stderr=subprocess.PIPE, - encoding="utf-8", - preexec_fn=os.setsid, - ) - poll_obj.register(process.stderr, select.POLLIN) - else: - process = subprocess.Popen( - command, - shell=True, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - encoding="utf-8", - preexec_fn=os.setsid, - ) - poll_obj.register(process.stdout, select.POLLIN) - - start_time = time.time() - try: - return self.poll(process, poll_obj, start_time) - finally: - try: - os.killpg(os.getpgid(process.pid), signal.SIGKILL) - except ProcessLookupError: - # This is an inevitable race condition, ignore - pass - - def poll(self, process, poll_obj, start_time): - output = "" - # None for any error code other than self.error_string - error_string = None - while True: - # polling on the output of the process with a timeout of 1 second - # to avoid busywaiting - if poll_obj.poll(1): - if self.use_stdout == 0: - output = process.stderr.readline() - else: - output = process.stdout.readline() - - if output.find(self.error_string) != -1: - # found the error code that we are searching for. - error_string = self.error_string - break - elif self.exit_early_on_error and output.find("ERROR") != -1: - # Found different error (bad cut) so we can just - # terminate early and ignore this cut. - break - - curr_time = time.time() - if (curr_time - start_time) > self.timeout: - print(f"Step {self.step_count} timed out!", flush=True) - break - - if process.poll() is not None: - break - - return error_string - - # A function to rename a smaller db file that produces the target error - # to the temporary name used to load a base db to perform further - # cutting on it. - def prepare_new_step(self): - # Delete the old temporary db file - if os.path.exists(self.temp_base_db_file): - os.remove(self.temp_base_db_file) - # Rename the new base db file to the temp name to keep it - # from overwriting across the two steps cut - if os.path.exists(self.base_db_file): - os.rename(self.base_db_file, self.temp_base_db_file) - - def clear_dont_touch_inst(self, inst): - inst.setDoNotTouch(False) - for iterm in inst.getITerms(): - net = iterm.getNet() - if net: - net.setDoNotTouch(False) - - def clear_dont_touch_net(self, net): - net.setDoNotTouch(False) - for iterm in net.getITerms(): - iterm.getInst().setDoNotTouch(False) - - def get_insts(self): - return self.base_db.getChip().getBlock().getInsts() - - def get_nets(self): - return self.base_db.getChip().getBlock().getNets() - - def get_elms(self): - if self.cut_level == cutLevel.Insts: - return self.get_insts() - return self.get_nets() - - def get_cuts(self): - return min(self.n * self.multiplier, len(self.get_elms())) - - # A function that cuts the block according to the given direction - # and ratio. It also uses the class cut level to identify - # whether to cut Insts or Nets. - def cut_block(self, index=0): - message = [f"Step {self.step_count}"] - if self.cut_level == cutLevel.Insts: # Insts cut level - elms = self.get_insts() - message += ["Insts level debugging"] - elif self.cut_level == cutLevel.Nets: # Nets cut level - elms = self.get_nets() - message += ["Nets level debugging"] - - message += [f"Insts {len(self.get_insts())}", f"Nets {len(self.get_nets())}"] - - num_elms = len(elms) - assert num_elms > 0 - - cuts = self.get_cuts() - start = num_elms * index // cuts - end = num_elms * (index + 1) // cuts - - cut_position_string = "#" * cuts - cut_position_string = ( - cut_position_string[:index] + "C" + cut_position_string[index + 1 :] - ) - message += [f"cut elements {end-start}"] - message += [f"timeout {ceil(self.timeout/60.0)} minutes"] - self.cut_elements(start, end) - - cuts = self.n * self.multiplier - print(", ".join(message), flush=True) - print(f"[{cut_position_string}]", flush=True) - - def cut_elements(self, start, end): - block = self.base_db.getChip().getBlock() - if self.cut_level == cutLevel.Insts: # Insts cut level - elms = block.getInsts() - elif self.cut_level == cutLevel.Nets: # Nets cut level - elms = block.getNets() - - for i in range(start, end): - elm = elms[i] - if self.cut_level == cutLevel.Insts: - self.clear_dont_touch_inst(elm) - elif self.cut_level == cutLevel.Nets: - self.clear_dont_touch_net(elm) - elm.destroy(elm) - - def remove_unused_masters(self): - # Create new clean dbDatabase - self.base_db = Design.createDetachedDb() - print(f"Reading {self.temp_base_db_file} file ") - self.base_db = odb.read_db(self.base_db, self.temp_base_db_file) - print("Removing unused masters...") - unused = self.base_db.removeUnusedMasters() - print(f"Removed {unused} masters.") - odb.write_db(self.base_db, self.temp_base_db_file) - - if self.dump_def != 0: - print("Writing def file") - odb.write_def( - self.base_db.getChip().getBlock(), self.temp_base_db_file[:-3] + "def" - ) - - if self.base_db is not None: - self.base_db.destroy(self.base_db) - self.base_db = None - - -if __name__ == "__main__": - opt = parser.parse_args() - debugger = deltaDebugger(opt) - debugger.debug() diff --git a/etc/test_deltaDebug.py b/etc/test_deltaDebug.py deleted file mode 100644 index 6d88aa4f00f..00000000000 --- a/etc/test_deltaDebug.py +++ /dev/null @@ -1,214 +0,0 @@ -import argparse -import sys -from unittest import TestCase -from unittest.mock import patch, MagicMock - -odb = MagicMock() -sys.modules["odb"] = odb -openroad = MagicMock() -sys.modules["openroad"] = openroad -import deltaDebug - -default_args = argparse.Namespace( - persistence=4, - use_stdout=True, - error_string="Iter: 100", - base_db_path="/dummy/path/base.db", - base_db_file=None, - original_db_file=None, - step="dummy_step", - timeout=100, - multiplier=1, - exit_early_on_error=True, - dump_def=True, -) - - -def mock_get_insts(mock_self): - return mock_self.insts - - -def mock_get_nets(mock_self): - return mock_self.nets - - -def mock_perform_step(mock_self, cut_index=-1): - before_cuts = mock_self.get_cuts() - - if cut_index == -1: - return mock_self.error_string, before_cuts - mock_self.cut_block(index=cut_index) - - after_cuts = mock_self.get_cuts() - if mock_self.check_error(mock_self.insts, mock_self.nets): - print(f"Error Code found: {mock_self.error_string}") - return mock_self.error_string, after_cuts - - mock_self.insts = list(mock_self.insts_saved) - mock_self.nets = list(mock_self.nets_saved) - return None, before_cuts - - -def mock_cut_elements(mock_self, start, end): - mock_self.insts_saved = list(mock_self.insts) - mock_self.nets_saved = list(mock_self.nets) - elements = ( - mock_self.insts - if mock_self.cut_level == deltaDebug.cutLevel.Insts - else mock_self.nets - ) - del elements[start:end] - - -def mock_prepare_new_step(mock_self): - pass - - -class TestDeltaDebug(TestCase): - @patch("os.path.exists", lambda x: True) - def setUp(self): - args = default_args - - self.perform_step_patch = patch.object( - deltaDebug.deltaDebugger, - "perform_step", - wraps=mock_perform_step, - autospec=True, - ) - self.get_insts_patch = patch.object( - deltaDebug.deltaDebugger, "get_insts", autospec=True - ) - self.get_nets_patch = patch.object( - deltaDebug.deltaDebugger, "get_nets", autospec=True - ) - self.cut_elements = patch.object( - deltaDebug.deltaDebugger, "cut_elements", autospec=True - ) - self.prepare_new_step = patch.object( - deltaDebug.deltaDebugger, "prepare_new_step", autospec=True - ) - self.shutil_copy_patch = patch("shutil.copy") - self.os_rename_patch = patch("os.rename") - - self.mock_perform_step = self.perform_step_patch.start() - self.mock_get_insts = self.get_insts_patch.start() - self.mock_get_nets = self.get_nets_patch.start() - self.mock_shutil_copy = self.shutil_copy_patch.start() - self.mock_os_rename = self.os_rename_patch.start() - self.mock_cut_elements = self.cut_elements.start() - self.mock_prepare_new_step = self.prepare_new_step.start() - - self.mock_perform_step.side_effect = mock_perform_step - self.mock_get_insts.side_effect = mock_get_insts - self.mock_get_nets.side_effect = mock_get_nets - self.mock_cut_elements.side_effect = mock_cut_elements - - self.debugger = deltaDebug.deltaDebugger(args) - - def tearDown(self): - self.perform_step_patch.stop() - self.get_insts_patch.stop() - self.get_nets_patch.stop() - self.shutil_copy_patch.stop() - self.os_rename_patch.stop() - self.cut_elements.stop() - self.prepare_new_step.stop() - - def test_pruned_to_one(self): - self.debugger.insts = list(range(10)) - self.debugger.nets = list(range(10)) - error_insts = [5] - error_nets = [7] - - def check_error(insts, nets): - return any(map(lambda x: x in error_insts, insts)) and any( - map(lambda x: x in error_nets, nets) - ) - - self.debugger.check_error = check_error - self.debugger.persistence = 4 - self.debugger.debug() - self.assertEqual(self.debugger.insts, error_insts) - self.assertEqual(self.debugger.nets, error_nets) - - def test_lots_down_to_one(self): - self.debugger.insts = list(range(100000)) - self.debugger.nets = list(range(100000)) - error_insts = set(range(50000, 50010)) - error_nets = set(range(70000, 80000)) - - def check_error(insts, nets): - return any(map(lambda x: x in error_insts, insts)) and any( - map(lambda x: x in error_nets, nets) - ) - - self.debugger.check_error = check_error - self.debugger.persistence = 4 - self.debugger.debug() - self.assertEqual(len(self.debugger.insts), 1) - self.assertEqual(len(self.debugger.nets), 1) - - def test_minimum_errors(self): - self.debugger.insts = list(range(1000)) - self.debugger.nets = list(range(1000)) - error_insts = set(range(500, 601)) - error_nets = set(range(700, 751)) - - def check_error(insts, nets): - return ( - any(map(lambda x: x in error_insts, insts)) - and len(insts) >= 100 - and any(map(lambda x: x in error_nets, nets)) - and len(nets) >= 75 - ) - - self.debugger.check_error = check_error - self.debugger.persistence = 6 - self.debugger.debug() - self.assertEqual(len(self.debugger.insts), 100) - self.assertEqual(len(self.debugger.nets), 75) - - def test_all_in_a_range(self): - self.debugger.insts = list(range(100)) - self.debugger.nets = list(range(100)) - error_insts = set(range(50, 60)) - error_nets = set(range(70, 90)) - - def check_error(insts, nets): - return all(map(lambda x: x in insts, error_insts)) and all( - map(lambda x: x in nets, error_nets) - ) - - self.debugger.check_error = check_error - self.debugger.persistence = 6 - self.debugger.debug() - self.assertEqual(set(self.debugger.insts), set(error_insts)) - self.assertEqual(set(self.debugger.nets), set(error_nets)) - - def test_no_insts(self): - self.debugger.insts = list(range(100)) - self.debugger.nets = list(range(100)) - error_nets = set(range(70, 90)) - - def check_error(insts, nets): - return len(insts) >= 0 and all(map(lambda x: x in nets, error_nets)) - - self.debugger.check_error = check_error - self.debugger.persistence = 6 - self.debugger.debug() - self.assertEqual(len(self.debugger.insts), 0) - self.assertEqual(set(self.debugger.nets), set(error_nets)) - - def test_no_nets(self): - self.debugger.insts = list(range(100)) - self.debugger.nets = list(range(100)) - error_insts = set(range(70, 90)) - - def check_error(insts, nets): - return len(nets) >= 0 and all(map(lambda x: x in insts, error_insts)) - - self.debugger.check_error = check_error - self.debugger.persistence = 6 - self.debugger.debug() - self.assertEqual(set(self.debugger.insts), set(error_insts)) - self.assertEqual(len(self.debugger.nets), 0) diff --git a/etc/test_whittle.py b/etc/test_whittle.py index f70618ad157..19c5c322f39 100644 --- a/etc/test_whittle.py +++ b/etc/test_whittle.py @@ -19,7 +19,7 @@ # --------------------------------------------------------------------------- # Mock helpers – simulate the in-memory element lists that the real TCL -# scripts would operate on. This mirrors the approach in test_deltaDebug.py. +# scripts would operate on. # --------------------------------------------------------------------------- @@ -112,7 +112,7 @@ def _setup_run(self, num_insts, num_nets, check_error, persistence=4): self.mock_prepare_new_step.side_effect = lambda self_: None # ------------------------------------------------------------------ - # Test cases (ported from test_deltaDebug.py) + # Test cases # ------------------------------------------------------------------ def test_pruned_to_one(self): diff --git a/etc/whittle.py b/etc/whittle.py index 2a568e9dfe2..462118cd45c 100644 --- a/etc/whittle.py +++ b/etc/whittle.py @@ -1,7 +1,6 @@ """Delta-debugging tool for minimising OpenROAD .odb test cases. -Unlike deltaDebug.py this script does *not* require Python to be compiled -into OpenROAD. Database manipulation is delegated to small TCL scripts +This script does *not* require Python to be compiled into OpenROAD. Database manipulation is delegated to small TCL scripts (whittle_cut.tcl, whittle_cleanup.tcl) that are executed via ``openroad -exit``. All imports are from the Python standard library, so any system ``python3`` works with no extra packages. @@ -132,13 +131,13 @@ def __init__(self, opt): self.step = opt.step self.original_base_db_file = os.path.join( - base_db_directory, f"deltaDebug_base_original_{base_db_name}" + base_db_directory, f"whittle_base_original_{base_db_name}" ) self.temp_base_db_file = os.path.join( - base_db_directory, f"deltaDebug_base_temp_{base_db_name}" + base_db_directory, f"whittle_base_temp_{base_db_name}" ) - self.deltaDebug_result_base_file = os.path.join( - base_db_directory, f"deltaDebug_base_result_{base_db_name}" + self.result_base_file = os.path.join( + base_db_directory, f"whittle_base_result_{base_db_name}" ) _script_dir = os.path.dirname(os.path.abspath(__file__)) @@ -418,13 +417,13 @@ def debug(self): self.cleanup_db(self.temp_base_db_file, self.temp_base_db_file) if os.path.exists(self.temp_base_db_file): - os.rename(self.temp_base_db_file, self.deltaDebug_result_base_file) + os.rename(self.temp_base_db_file, self.result_base_file) if os.path.exists(self.original_base_db_file): os.rename(self.original_base_db_file, self.base_db_file) print("___________________________________") - print(f"Resultant file is {self.deltaDebug_result_base_file}") - print("Delta Debugging Done!") + print(f"Resultant file is {self.result_base_file}") + print("Whittling Done!") def main(args=None): From 3c824138f3e9085b9ead27974719bb9356551009 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=98yvind=20Harboe?= Date: Fri, 13 Mar 2026 08:56:32 +0100 Subject: [PATCH 2/4] add progress monitoring to whittle.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Show periodic [whittle] status with phase, element counts, .odb size, elapsed time. Display tail of step log after 5 minutes of waiting. Print final summary with before/after .odb sizes. Co-Authored-By: Claude Opus 4.6 Signed-off-by: Øyvind Harboe --- etc/test_whittle.py | 30 ++++++++++++++++ etc/whittle.py | 83 +++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 111 insertions(+), 2 deletions(-) diff --git a/etc/test_whittle.py b/etc/test_whittle.py index 19c5c322f39..8663d253597 100644 --- a/etc/test_whittle.py +++ b/etc/test_whittle.py @@ -1,4 +1,5 @@ import argparse +import io from unittest import TestCase from unittest.mock import patch, MagicMock @@ -196,6 +197,35 @@ def check_error(insts, nets): self.assertEqual(set(self.whittler._insts), error_insts) self.assertEqual(len(self.whittler._nets), 0) + def test_progress_output(self): + error_insts = [5] + error_nets = [7] + + def check_error(insts, nets): + return any(x in error_insts for x in insts) and any( + x in error_nets for x in nets + ) + + self._setup_run(10, 10, check_error) + + captured = io.StringIO() + with patch("sys.stdout", captured): + self.whittler.debug() + + output = captured.getvalue() + self.assertIn("[whittle]", output) + self.assertIn("Phase: Insts", output) + self.assertIn("Phase: Nets", output) + self.assertIn("Elapsed:", output) + self.assertIn("Whittling Done!", output) + + def test_format_duration(self): + self.assertEqual(whittle.Whittler.format_duration(30), "30s") + self.assertEqual(whittle.Whittler.format_duration(90), "1m") + self.assertEqual(whittle.Whittler.format_duration(120), "2m") + self.assertEqual(whittle.Whittler.format_duration(3661), "1h 01m") + self.assertEqual(whittle.Whittler.format_duration(7200), "2h 00m") + class TestWhittleTclInterface(TestCase): """Test the subprocess/TCL interface without algorithm mocks.""" diff --git a/etc/whittle.py b/etc/whittle.py index 462118cd45c..b1d10eb9961 100644 --- a/etc/whittle.py +++ b/etc/whittle.py @@ -35,10 +35,12 @@ import subprocess import sys import time +from collections import deque from math import ceil PERSISTENCE_RANGE = range(1, 7) CUT_MULTIPLE = range(1, 128) +LOG_TAIL_DELAY = 300 # seconds before showing step log tail class CutLevel(enum.Enum): @@ -157,6 +159,56 @@ def __init__(self, opt): self.num_insts = 0 self.num_nets = 0 + # Progress tracking. + self._start_time = None + self._original_insts = 0 + self._original_nets = 0 + self._original_odb_size = 0 + + # ----------------------------------------------------------------- + # Progress helpers + # ----------------------------------------------------------------- + + @staticmethod + def format_duration(seconds): + """Format seconds into a human-readable duration string.""" + seconds = int(seconds) + if seconds < 60: + return f"{seconds}s" + if seconds < 3600: + return f"{seconds // 60}m" + return f"{seconds // 3600}h {seconds % 3600 // 60:02d}m" + + @staticmethod + def file_size_mb(path): + """Return file size in MB, or 0 if the file doesn't exist.""" + try: + return os.path.getsize(path) / (1024 * 1024) + except OSError: + return 0 + + def _record_original_counts(self): + """Snapshot the starting element counts and .odb size.""" + self._start_time = time.time() + self._original_insts = self.num_insts + self._original_nets = self.num_nets + self._original_odb_size = self.file_size_mb(self.base_db_file) + + def print_progress(self): + """Print a [whittle] status line with current counts and ETA.""" + elapsed = time.time() - self._start_time + phase = "Insts" if self.cut_level == CutLevel.Insts else "Nets" + odb_size = self.file_size_mb(self.temp_base_db_file) + parts = [ + f"[whittle] Phase: {phase}", + f"Step {self.step_count}", + f"Insts: {self.num_insts}", + f"Nets: {self.num_nets}", + f".odb: {odb_size:.0f}MB (was {self._original_odb_size:.0f}MB)", + f"Elapsed: {self.format_duration(elapsed)}", + ] + print(", ".join(parts), flush=True) + # ----------------------------------------------------------------- # TCL helpers – these shell out to ``openroad -exit`` # ----------------------------------------------------------------- @@ -274,6 +326,8 @@ def run_command(self, command): def _poll(self, process, poll_obj, start_time): error_string = None + log_tail = deque(maxlen=10) + tail_shown = False while True: if poll_obj.poll(1): if not self.use_stdout: @@ -281,16 +335,30 @@ def _poll(self, process, poll_obj, start_time): else: output = process.stdout.readline() + if output: + log_tail.append(output.rstrip()) + if output.find(self.error_string) != -1: error_string = self.error_string break elif self.exit_early_on_error and output.find("ERROR") != -1: break - if (time.time() - start_time) > self.timeout: + elapsed = time.time() - start_time + if elapsed > self.timeout: print(f"Step {self.step_count} timed out!", flush=True) break + if not tail_shown and elapsed > LOG_TAIL_DELAY and log_tail: + tail_shown = True + print( + f"[whittle] Step running for {self.format_duration(elapsed)}, " + f"last {len(log_tail)} lines:", + flush=True, + ) + for line in log_tail: + print(f" | {line}", flush=True) + if process.poll() is not None: break @@ -371,8 +439,9 @@ def debug(self): shutil.copy(self.base_db_file, self.original_base_db_file) os.rename(self.base_db_file, self.temp_base_db_file) - # Read initial element counts. + # Read initial element counts and record starting state. self.read_counts(self.temp_base_db_file) + self._record_original_counts() if self.timeout is None: self.timeout = 1e6 @@ -386,6 +455,8 @@ def debug(self): sys.exit(1) for self.cut_level in (CutLevel.Insts, CutLevel.Nets): + phase = "Insts" if self.cut_level == CutLevel.Insts else "Nets" + print(f"[whittle] === Starting Phase: {phase} ===", flush=True) while True: err = None self.n = 2 @@ -395,6 +466,7 @@ def debug(self): error_in_range = None j = 0 while j == 0 or j < cuts: + self.print_progress() current_err, cuts = self.perform_step(cut_index=j) self.step_count += 1 if current_err is not None: @@ -421,7 +493,14 @@ def debug(self): if os.path.exists(self.original_base_db_file): os.rename(self.original_base_db_file, self.base_db_file) + elapsed = time.time() - self._start_time + result_size = self.file_size_mb(self.result_base_file) print("___________________________________") + print(f"[whittle] Total time: {self.format_duration(elapsed)}") + print( + f"[whittle] .odb: {self._original_odb_size:.0f}MB" + f" -> {result_size:.0f}MB" + ) print(f"Resultant file is {self.result_base_file}") print("Whittling Done!") From a967f322910cfcc20c266a95f4d544446f3d646b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=98yvind=20Harboe?= Date: Fri, 13 Mar 2026 08:57:21 +0100 Subject: [PATCH 3/4] document whittle.py progress monitoring and Claude workflow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 4.6 Signed-off-by: Øyvind Harboe --- docs/user/Bazel.md | 28 ++++++++++++++++++++++++++++ test/orfs/README.md | 10 ++++++++++ 2 files changed, 38 insertions(+) diff --git a/docs/user/Bazel.md b/docs/user/Bazel.md index 47315c1bcd6..c6a92d178e8 100644 --- a/docs/user/Bazel.md +++ b/docs/user/Bazel.md @@ -405,3 +405,31 @@ an ORFS checkout): This should eventually leave you with a whittled down .odb file. Copy the whittled down .odb file into the correct place for 3_2_place_iop.odb, then create a bug report: tmp/test/orfs/gcd/gcd_place_deps/make global_place_issue + +### Monitoring progress + +whittle.py prints `[whittle]` status lines showing the current phase, +element counts, .odb file size, and elapsed time. After a step runs for +more than 5 minutes, whittle.py also shows the last 10 lines of the +step's log output so you can tell what the step is doing. + +If the .odb size is not shrinking after 20+ steps, try different +parameters (`--persistence 1` for a coarser first pass, or a higher +`--multiplier`). If each step takes more than 10 minutes, check that +`--error_string` is specific enough (avoid generic strings like "ERROR"). + +### Using Claude with whittle.py + +Point Claude at a GitHub issue that has an attached tarball artifact +(from `make *_issue`). Claude can download the artifact, reproduce the +bug with the latest OpenROAD, run whittle.py, and upload a smaller +test case. + +| Scenario | Recommended flags | +| --- | --- | +| Global placement bugs | `--error_string GPL-XXXX --persistence 3 --multiplier 2` | +| Fast initial reduction | `--persistence 1` first, then increase | +| Large designs (>100K insts) | Start with `--timeout 600` | + +See the `/triage-issue` Claude skill in `.claude/skills/triage-issue/` +for the full step-by-step workflow. diff --git a/test/orfs/README.md b/test/orfs/README.md index ee3d2905322..1fc7d4a3967 100644 --- a/test/orfs/README.md +++ b/test/orfs/README.md @@ -229,3 +229,13 @@ cp $1 test/orfs/gcd/ Next, run sv-bugpoint to whittle `test/orfs/gcd/gcd.v` down to a minimal test case: ~/sv-bugpoint/build/sv-bugpoint fail check.sh test/orfs/gcd/gcd.v + +## Using whittle.py to minimize .odb files + +While sv-bugpoint minimizes Verilog source files, `whittle.py` minimizes +`.odb` database files by iteratively removing instances and nets. This is +useful when the bug is in placement, routing, or other physical stages +where Verilog reduction would not help. + +See [Bazel.md](../../docs/user/Bazel.md#whittling-down-odb-files) for +detailed instructions and recommended flags. From 30f5080c284f155d8c5ef893058665f3406944bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=98yvind=20Harboe?= Date: Fri, 13 Mar 2026 08:59:47 +0100 Subject: [PATCH 4/4] add /triage-issue Claude skill for bug minimization MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 4.6 Signed-off-by: Øyvind Harboe --- .claude/skills/triage-issue/SKILL.md | 128 +++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 .claude/skills/triage-issue/SKILL.md diff --git a/.claude/skills/triage-issue/SKILL.md b/.claude/skills/triage-issue/SKILL.md new file mode 100644 index 00000000000..46f5d089d2a --- /dev/null +++ b/.claude/skills/triage-issue/SKILL.md @@ -0,0 +1,128 @@ +--- +name: triage-issue +description: > + Triage an OpenROAD GitHub issue by reproducing the bug and + minimizing the test case with whittle.py. Use when an issue + has an attached tarball artifact (.tar.gz) from `make *_issue`. +argument-hint: +--- + +# Triage OpenROAD Issue + +You are triaging OpenROAD issue **$ARGUMENTS**. + +## 1. Fetch issue details + +```bash +gh issue view $ARGUMENTS --repo The-OpenROAD-Project/OpenROAD \ + --json title,body,labels,state,comments +``` + +Look for: +- Error string (e.g. `GPL-0305`, `GPL-0307`, `DRT-XXXX`) +- Attached tarball URL (from `make *_issue`) +- OpenROAD version the bug was reported against + +## 2. Download and extract artifact + +Download any `.tar.gz` attached to the issue body or comments. +Extract into a working directory: + +```bash +mkdir -p /tmp/triage-$ARGUMENTS +cd /tmp/triage-$ARGUMENTS +tar xzf +cd +``` + +## 3. Fix the run script + +The `run-me-*.sh` scripts from `make *_issue` often need two fixes: + +```bash +# Add set -e to exit on error +sed -i '2i set -e' run-me-*.sh + +# Add -exit so openroad exits after the tcl script +sed -i 's/openroad -no_init/openroad -exit -no_init/g' run-me-*.sh +sed -i 's/openroad -no_splash/openroad -exit -no_splash/g' run-me-*.sh +``` + +## 4. Build OpenROAD + +Build from the OpenROAD source tree: + +```bash +cd /OpenROAD +bazelisk build :openroad +``` + +The binary is at `bazel-bin/openroad`. Export it: + +```bash +export OPENROAD_EXE=$(pwd)/bazel-bin/openroad +``` + +## 5. Reproduce the bug + +Run the step command and confirm the error string appears: + +```bash +cd /tmp/triage-$ARGUMENTS/ +./run-me-*.sh 2>&1 | tee reproduce.log +grep -c "" reproduce.log +``` + +If the bug does NOT reproduce with the latest OpenROAD, report this +on the issue -- the bug may have been fixed. + +## 6. Run whittle.py + +```bash +python3 /OpenROAD/etc/whittle.py \ + --error_string "" \ + --base_db_path .odb \ + --use_stdout --exit_early_on_error \ + --step "./run-me-*.sh" \ + --persistence 3 --multiplier 2 +``` + +### Monitoring progress + +Watch the `[whittle]` lines. Key things to check: + +- **ETA growing?** The design may be too large for the current + persistence level. Try `--persistence 1` for a coarse first pass. +- **.odb size not shrinking?** The error may depend on most of the + design. Try increasing `--multiplier`. +- **Step timeout too long?** Use `--timeout 300` to cap each step + at 5 minutes. +- **After 5 minutes** of a step, whittle.py shows the tail of the + step's log so you can see what it is doing. + +### When to abort + +- If after 20+ steps the .odb size has not changed, abort and try + different parameters. +- If the step itself takes >10 minutes, consider whether the error + string is specific enough (avoid generic strings like "ERROR"). + +## 7. Upload results + +Create a new tarball with the whittled .odb: + +```bash +cp whittle_base_result_*.odb +tar czf whittled-$ARGUMENTS.tar.gz / +``` + +Comment on the issue with before/after stats: + +```bash +gh issue comment $ARGUMENTS --repo The-OpenROAD-Project/OpenROAD \ + --body "Whittled test case: original NNN insts -> MMM insts, \ +.odb size: XXX MB -> YYY MB. Attached whittled tarball." +``` + +Upload the tarball to the issue comment via the GitHub web UI +(gh CLI does not support file attachments on comments).