Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /promptdriven_pdd /tests /isolated_verify.py
| #!/usr/bin/env python3 | |
| """ | |
| Isolated test harness for the verify command. | |
| This script creates an isolated environment for verification testing, | |
| ensuring the code being analyzed is the same code being executed. | |
| """ | |
| import os | |
| import sys | |
| import shutil | |
| import tempfile | |
| import argparse | |
| import subprocess | |
| from pathlib import Path | |
| def create_isolated_environment(prompt_file, code_file, program_file, output_dir=None): | |
| """ | |
| Create an isolated environment for verification testing. | |
| Args: | |
| prompt_file: Path to the prompt file | |
| code_file: Path to the code file to verify | |
| program_file: Path to the program that tests the code | |
| output_dir: Optional specific directory to use (if None, creates temp dir) | |
| Returns: | |
| tuple: (temp_dir, isolated_prompt_path, isolated_code_path, isolated_program_path, wrapper_path) | |
| """ | |
| # Create a temporary directory if output_dir is not provided | |
| if output_dir: | |
| temp_dir = output_dir | |
| os.makedirs(temp_dir, exist_ok=True) | |
| else: | |
| temp_dir = tempfile.mkdtemp(prefix="isolated_verify_") | |
| # Copy the files to the temporary directory | |
| code_basename = os.path.basename(code_file) | |
| program_basename = os.path.basename(program_file) | |
| prompt_basename = os.path.basename(prompt_file) | |
| isolated_code_path = os.path.join(temp_dir, code_basename) | |
| isolated_program_path = os.path.join(temp_dir, program_basename) | |
| isolated_prompt_path = os.path.join(temp_dir, prompt_basename) | |
| shutil.copy2(code_file, isolated_code_path) | |
| shutil.copy2(program_file, isolated_program_path) | |
| shutil.copy2(prompt_file, isolated_prompt_path) | |
| # Create __init__.py to make it a proper package | |
| with open(os.path.join(temp_dir, "__init__.py"), "w") as f: | |
| f.write("# Auto-generated by isolated verification harness\n") | |
| # Create a wrapper module that properly handles imports | |
| module_base = os.path.splitext(code_basename)[0] | |
| wrapper_path = os.path.join(temp_dir, f"{module_base}_wrapper.py") | |
| with open(wrapper_path, "w") as f: | |
| f.write(f'''# Robust wrapper module generated by isolated verification harness | |
| import os | |
| import sys | |
| import importlib.util | |
| def import_module_from_file(file_path, module_name=None): | |
| """Import a module from a file path dynamically.""" | |
| if module_name is None: | |
| module_name = os.path.basename(file_path).replace('.py', '') | |
| spec = importlib.util.spec_from_file_location(module_name, file_path) | |
| if not spec: | |
| raise ImportError(f"Could not load spec for {{file_path}}") | |
| module = importlib.util.module_from_spec(spec) | |
| sys.modules[module_name] = module | |
| spec.loader.exec_module(module) | |
| return module | |
| # Get the absolute path of the directory containing this script | |
| current_dir = os.path.dirname(os.path.abspath(__file__)) | |
| # Add the current directory to sys.path for local imports | |
| if current_dir not in sys.path: | |
| sys.modules["pdd"] = type('', (), {{}})() # Create a fake pdd module | |
| sys.modules["pdd.{module_base}"] = type('', (), {{}})() # Create a fake pdd.module | |
| sys.path.insert(0, current_dir) | |
| # Import from the local file | |
| try: | |
| # Try direct import first | |
| {module_base}_module = import_module_from_file( | |
| os.path.join(current_dir, "{code_basename}"), | |
| "{module_base}" | |
| ) | |
| # Export all attributes from the module | |
| for attr_name in dir({module_base}_module): | |
| if not attr_name.startswith('_'): | |
| globals()[attr_name] = getattr({module_base}_module, attr_name) | |
| except Exception as e: | |
| print(f"Error importing {module_base}: {{e}}") | |
| # Provide dummy functions for tests | |
| def get_extension(language): | |
| print(f"WARNING: Using fallback function due to import error!") | |
| return "" | |
| ''') | |
| # Fix imports in the program file to use local module instead of package imports | |
| fix_program_imports(isolated_program_path, code_basename, wrapper_path) | |
| print(f"Created isolated test environment in {temp_dir}") | |
| print(f" Code: {isolated_code_path}") | |
| print(f" Program: {isolated_program_path}") | |
| print(f" Prompt: {isolated_prompt_path}") | |
| print(f" Wrapper: {wrapper_path}") | |
| return temp_dir, isolated_prompt_path, isolated_code_path, isolated_program_path, wrapper_path | |
| def fix_program_imports(program_path, module_name, wrapper_path=None): | |
| """ | |
| Fix imports in the program file to use local modules. | |
| Args: | |
| program_path: Path to the program file | |
| module_name: Name of the module file (with .py extension) | |
| wrapper_path: Path to the wrapper module (if any) | |
| """ | |
| try: | |
| with open(program_path, 'r') as f: | |
| content = f.read() | |
| # Get the module base name without extension | |
| module_base = os.path.splitext(module_name)[0] | |
| if wrapper_path: | |
| # If we have a wrapper, use it for all imports | |
| wrapper_base = os.path.splitext(os.path.basename(wrapper_path))[0] | |
| patterns = [ | |
| (f"from pdd.{module_base} import", f"from {wrapper_base} import"), | |
| (f"from pdd import {module_base}", f"import {wrapper_base} as {module_base}"), | |
| (f"import pdd.{module_base}", f"import {wrapper_base} as {module_base}"), | |
| ] | |
| else: | |
| # Otherwise use direct imports | |
| patterns = [ | |
| (f"from pdd.{module_base} import", f"from {module_base} import"), | |
| (f"from pdd import {module_base}", f"import {module_base}"), | |
| (f"import pdd.{module_base}", f"import {module_base}"), | |
| ] | |
| for old, new in patterns: | |
| content = content.replace(old, new) | |
| with open(program_path, 'w') as f: | |
| f.write(content) | |
| print(f"Updated imports in {os.path.basename(program_path)}") | |
| except Exception as e: | |
| print(f"Warning: Could not fix imports in program file: {e}") | |
| def run_pdd_command(cmd, *args, **kwargs): | |
| """ | |
| Run a PDD command with the given arguments. | |
| Args: | |
| cmd: The PDD command to run | |
| *args: Additional command line arguments | |
| **kwargs: Additional keyword arguments: | |
| - force: Whether to use --force flag | |
| - strength: Model strength to use | |
| - temperature: Model temperature to use | |
| - budget: Cost budget for verification | |
| - max_attempts: Maximum attempts for verification | |
| - env_dir: Directory to add to PYTHONPATH | |
| Returns: | |
| tuple: (exit_code, stdout, stderr) | |
| """ | |
| pdd_script = os.environ.get('PDD_SCRIPT', 'pdd') | |
| # Extract special kwargs | |
| force = kwargs.pop('force', True) | |
| strength = kwargs.pop('strength', 0.85) | |
| temperature = kwargs.pop('temperature', 1.0) | |
| budget = kwargs.pop('budget', None) | |
| max_attempts = kwargs.pop('max_attempts', None) | |
| env_dir = kwargs.pop('env_dir', None) | |
| # Build command | |
| cmd_args = [pdd_script] | |
| if force: | |
| cmd_args.append('--force') | |
| cmd_args.extend([ | |
| '--strength', str(strength), | |
| '--temperature', str(temperature) | |
| ]) | |
| # Add the command | |
| cmd_args.append(cmd) | |
| # Add budget and max attempts if specified | |
| if budget is not None: | |
| cmd_args.extend(['--budget', str(budget)]) | |
| if max_attempts is not None: | |
| cmd_args.extend(['--max-attempts', str(max_attempts)]) | |
| # Add the remaining arguments | |
| cmd_args.extend(args) | |
| # Prepare environment variables | |
| env = os.environ.copy() | |
| if env_dir: | |
| if 'PYTHONPATH' in env: | |
| env['PYTHONPATH'] = f"{env_dir}{os.pathsep}{env['PYTHONPATH']}" | |
| else: | |
| env['PYTHONPATH'] = env_dir | |
| print(f"Added {env_dir} to PYTHONPATH") | |
| # Print the command | |
| print(f"Running: {' '.join(cmd_args)}") | |
| # Run the command | |
| process = subprocess.run( | |
| cmd_args, | |
| capture_output=True, | |
| text=True, | |
| check=False, | |
| env=env | |
| ) | |
| return process.returncode, process.stdout, process.stderr | |
| def main(): | |
| parser = argparse.ArgumentParser(description='Run isolated verification tests') | |
| parser.add_argument('--prompt-file', required=True, help='Path to the prompt file') | |
| parser.add_argument('--code-file', required=True, help='Path to the code file to verify') | |
| parser.add_argument('--program-file', required=True, help='Path to the program file that tests the code') | |
| parser.add_argument('--output-results', help='Path to save verification results') | |
| parser.add_argument('--output-code', help='Path to save the verified code') | |
| parser.add_argument('--output-dir', help='Custom directory to use for isolation (default: temp dir)') | |
| parser.add_argument('--max-attempts', type=int, default=3, help='Maximum verification attempts') | |
| parser.add_argument('--budget', type=float, default=5.0, help='Cost budget for verification') | |
| parser.add_argument('--strength', type=float, default=0.85, help='Model strength') | |
| parser.add_argument('--temperature', type=float, default=1.0, help='Model temperature') | |
| parser.add_argument('--force', action='store_true', help='Force overwrite of output files') | |
| parser.add_argument('--keep-temp', action='store_true', help='Keep temporary directory after completion') | |
| parser.add_argument('--loop', action='store_true', help='Run in iterative loop mode') | |
| parser.add_argument('--verbose', action='store_true', help='Enable verbose output') | |
| args = parser.parse_args() | |
| # Create isolated environment | |
| temp_dir, isolated_prompt, isolated_code, isolated_program, wrapper_path = create_isolated_environment( | |
| args.prompt_file, args.code_file, args.program_file, args.output_dir | |
| ) | |
| # Extract module base name | |
| module_base = os.path.splitext(os.path.basename(args.code_file))[0] | |
| wrapper_base = f"{module_base}_wrapper" | |
| try: | |
| # Create a simple verification program that tests the module in isolation | |
| test_script_path = os.path.join(temp_dir, f"verify_test_{module_base}.py") | |
| with open(test_script_path, "w") as f: | |
| f.write(f'''#!/usr/bin/env python3 | |
| """ | |
| Simple verification test script generated by isolated_verify.py | |
| This runs the original program but ensures it uses the local module. | |
| """ | |
| import os | |
| import sys | |
| import importlib.util | |
| # Add the current directory to sys.path | |
| current_dir = os.path.dirname(os.path.abspath(__file__)) | |
| if current_dir not in sys.path: | |
| sys.path.insert(0, current_dir) | |
| # Import the wrapper module | |
| try: | |
| import {wrapper_base} | |
| # Now run the original program which should use the local module | |
| import {os.path.splitext(os.path.basename(isolated_program))[0]} | |
| except Exception as e: | |
| print(f"Error running verification test: {{e}}") | |
| sys.exit(1) | |
| ''') | |
| # Make the test script executable | |
| os.chmod(test_script_path, 0o755) | |
| # Try running the verification test script directly first to ensure imports work | |
| print(f"\nRunning verification test script to check imports...") | |
| test_result = subprocess.run( | |
| [sys.executable, test_script_path], | |
| capture_output=True, | |
| text=True | |
| ) | |
| if test_result.returncode != 0: | |
| print(f"Warning: Verification test script failed with code {test_result.returncode}") | |
| print("This may indicate import issues in the isolated environment.") | |
| print("\nSTDOUT:") | |
| print(test_result.stdout) | |
| print("\nSTDERR:") | |
| print(test_result.stderr) | |
| else: | |
| print(f"Verification test script ran successfully, imports are working correctly.") | |
| # Prepare verification command arguments | |
| verify_args = [] | |
| # Add output paths if specified | |
| if args.output_results: | |
| verify_args.extend(['--output-results', args.output_results]) | |
| if args.output_code: | |
| verify_args.extend(['--output-code', args.output_code]) | |
| # Add loop mode if specified | |
| if args.loop: | |
| verify_args.append('--loop') | |
| # Always use the isolated program as the verification program | |
| verify_args.extend(['--verification-program', isolated_program]) | |
| # Add the input files - use isolated paths | |
| verify_args.extend([isolated_prompt, isolated_code, isolated_program]) | |
| if args.verbose: | |
| print(f"\nUsing isolated files for verification:") | |
| print(f" Prompt: {isolated_prompt}") | |
| print(f" Code: {isolated_code}") | |
| print(f" Program: {isolated_program}") | |
| print(f" Wrapper: {wrapper_path}") | |
| print(f" Environment dir: {temp_dir}") | |
| # Run the verification command in the isolated environment | |
| exit_code, stdout, stderr = run_pdd_command( | |
| 'verify', | |
| *verify_args, | |
| force=args.force, | |
| strength=args.strength, | |
| temperature=args.temperature, | |
| budget=args.budget, | |
| max_attempts=args.max_attempts, | |
| env_dir=temp_dir # Add the temp dir to PYTHONPATH | |
| ) | |
| # Print the output if verbose | |
| if args.verbose: | |
| print("\n--- STDOUT ---") | |
| print(stdout) | |
| if stderr: | |
| print("\n--- STDERR ---") | |
| print(stderr) | |
| # Copy any generated files back if they exist | |
| if args.output_code and os.path.exists(args.output_code): | |
| # Copy the verified code back to the original code file | |
| # Only if the verification was successful (exit_code == 0) | |
| if exit_code == 0: | |
| print(f"\nVerification successful, copying verified code to {args.code_file}") | |
| shutil.copy2(args.output_code, args.code_file) | |
| else: | |
| print(f"\nVerification failed with exit code {exit_code}") | |
| # Return the verification exit code | |
| return exit_code | |
| finally: | |
| # Clean up the temporary directory if not keeping it | |
| if not args.keep_temp and temp_dir and os.path.exists(temp_dir) and not args.output_dir: | |
| shutil.rmtree(temp_dir) | |
| print(f"Removed temporary directory: {temp_dir}") | |
| if __name__ == "__main__": | |
| sys.exit(main()) |
Xet Storage Details
- Size:
- 14.6 kB
- Xet hash:
- 05300ff4b1a6e7ba0fd51d30d20bf97296d5e8071b70c8d6bed1799e9657b958
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.