All files / server/services/sandbox execution-manager.ts

73.7% Statements 185/251
49.57% Branches 59/119
70% Functions 21/30
74.58% Lines 179/240

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697                                                                    13x 13x 13x 13x 13x 13x     13x                                                                                                                                                                                               44x 44x                                     44x 44x 44x 44x 44x 44x 44x 44x             16x     16x 16x           16x     16x                                     16x 16x     16x 16x 16x 16x     16x     16x       1x   1x                               1x 1x 1x 1x 1x     1x 1x       16x 16x   16x   16x 16x   16x           16x           16x   6x 6x 6x 1x   6x 6x   6x 6x                           16x   16x 16x       16x 16x     16x   16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x                     16x 16x 16x 16x                         13x         13x                         16x   16x 3x 13x     13x                         3x 3x 3x   3x             3x 3x     3x     3x           3x 3x 8x 3x 3x         3x 3x       3x 3x 3x 3x   3x 1x 1x 1x     3x   3x       3x       3x 3x   3x                   3x           3x                     3x 4x 4x 4x       4x       4x     3x       3x 4x 4x                                                           13x 13x     13x 13x 13x   13x 13x 13x 7x     7x   7x 6x 6x       1x       1x     1x   6x 6x 6x 6x 6x 6x 6x 6x 6x                         1x   1x         1x                                         1x 1x   1x                   1x                 1x 1x 1x   1x         1x                       1x   1x 1x 1x 1x 1x   1x 1x 1x       1x             1x 1x               31x 30x 30x             23x                  
// execution-manager.ts
// Orchestrates the complete simulation lifecycle (prepare, compile, run)
// Extracted from SandboxRunner to reduce runner complexity
 
import { randomUUID } from "node:crypto";
import { Logger } from "@shared/logger";
import type { IOPinRecord } from "@shared/schema";
import type { PinStateChange } from "@shared/types/arduino.types";
import type { IProcessController } from "../process-controller";
import { ArduinoOutputParser as StderrParser } from "../arduino-output-parser";
import { RegistryManager } from "../registry-manager";
import { SimulationTimeoutManager } from "../simulation-timeout-manager";
import { SketchFileBuilder } from "../sketch-file-builder";
import { LocalCompiler } from "../local-compiler";
import { PinStateBatcher, type PinStateBatch } from "../pin-state-batcher";
import { SerialOutputBatcher } from "../serial-output-batcher";
import type { RunSketchOptions } from "../run-sketch-types";
import { getDockerCompileSemaphore } from "./docker-compile-semaphore";
import { DockerManager } from "./docker-manager";
import { StreamHandler } from "./stream-handler";
import { FilesystemHelper } from "./filesystem-helper";
import { config } from "../../config";
import { normalizeBaudrate, normalizeSimulationTimeout } from "@shared/input-limits";
import { canTransition } from "../simulation-state-machine";
import { createProcessExecutionPort, type ProcessExecution } from "../process-execution-port";
import { OutputCollector } from "../output-collector";
import { flushMessageQueue, flushBatchers, cleanupDockerContainer } from "./execution-phases/cleanup-phase";
import { scheduleExecutionTimeout } from "./execution-phases/timeout-phase";
import { createStreamCallbacks, delegateParsedLineToStreamHandler, handleStderrFallbackData } from "./execution-phases/stream-phase";
import { runLocalStart, runDockerStart, type LocalStartContext, type DockerStartContext, type DockerStartParams, type TransitionToFn } from "./execution-phases/start-phase";
import { decideExecutionRoute } from "./execution-phases/router-phase";
import { performCompilation, type PrepareContext } from "./execution-phases/prepare-phase";
import { compileMetricsTracker } from "../server-metrics";
 
export enum SimulationState {
  STOPPED = "stopped",
  STARTING = "starting",
  RUNNING = "running",
  PAUSED = "paused",
  ERROR = "error",
}
 
export const SANDBOX_CONFIG = {
  dockerImage: config.sandbox.dockerImage,
  useDocker: config.simulationMode === "docker-sandbox",
  maxMemoryMB: config.sandbox.resources.memoryMB,
  cpuLimit: config.sandbox.resources.cpuLimit,
  maxCpuPercent: Math.round(Number.parseFloat(config.sandbox.resources.cpuLimit) * 100),
  pidsLimit: config.sandbox.resources.pidsLimit,
  maxExecutionTimeSec: config.sandbox.resources.maxExecutionTimeSec,
  maxOutputBytes: config.sandbox.resources.maxOutputBytes,
  noNetwork: true,
  readOnlyFs: true,
  dropCapabilities: true,
};
 
// Type aliases for callbacks
// Output / error / pin state callbacks (from sandbox runner to consumers)
type OutputCallback = (line: string, isComplete?: boolean) => void;
type PinStateCallback = (pin: number, type: PinStateChange, value: number) => void;
type ErrorCallback = (line: string) => void;
 
export interface TelemetryMetrics {
  timestamp: number;
  intendedPinChangesPerSecond: number;
  actualPinChangesPerSecond: number;
  droppedPinChangesPerSecond: number;
  batchesPerSecond: number;
  avgStatesPerBatch: number;
  serialOutputPerSecond: number;
  serialBytesPerSecond: number;
  serialBytesTotal: number;
  serialIntendedBytesPerSecond: number;
  serialDroppedBytesPerSecond: number;
}
 
type TelemetryCallback = (metrics: TelemetryMetrics) => void;
 
type ProcessMessage =
  | { type: "pinState"; data: { pin: number; stateType: PinStateChange; value: number } }
  | { type: "output"; data: { line: string; isComplete?: boolean } }
  | { type: "error"; data: { line: string } };
 
type DockerState = {
  isCompilePhase: { value: boolean };
  compileErrorBuffer: { value: string };
  compileSuccessSent: { value: boolean };
  totalOutputBytes: { value: number };
  processStartTime: number | null;
  stderrFallbackBuffer: string;
  flushTimer: NodeJS.Timeout | null;
};
 
interface ExecutionCallbacks {
  onOutput: OutputCallback;
  onError: ErrorCallback;
  onPinState?: PinStateCallback;
}
 
type IORegistryCallback = (registry: IOPinRecord[], baudrate: number | undefined, reason?: string) => void;
 
// Nullable type aliases
type Nullable<T> = T | null;
 
export interface ExecutionState {
  outputBuffer: string;
  outputBufferIndex: number;
  isSendingOutput: boolean;
  totalOutputBytes: number;
  messageQueue: ProcessMessage[];
  pauseStartTime: Nullable<number>;
  totalPausedTime: number;
  isCompiling: boolean;
  currentSketchDir: Nullable<string>;
  currentRegistryFile: Nullable<string>;
  processStartTime: Nullable<number>;
  onOutputCallback: Nullable<OutputCallback>;
  pinStateCallback: Nullable<PinStateCallback>;
  errorCallback: Nullable<ErrorCallback>;
  telemetryCallback: Nullable<TelemetryCallback>;
  ioRegistryCallback?: IORegistryCallback;
  pinStateBatcher: Nullable<PinStateBatcher>;
  serialOutputBatcher: Nullable<SerialOutputBatcher>;
  backpressurePaused: boolean;
  baudrate: number;
  stderrFallbackBuffer: string;
  flushTimer: Nullable<NodeJS.Timeout>;
  state: SimulationState;
  processKilled: boolean;
  pendingCleanup: boolean;
  processController: IProcessController;
  currentContainerName?: string;
  dockerAvailable?: boolean;
  dockerImageBuilt?: boolean;
  outputCollector?: OutputCollector;
}
 
export class ExecutionManager {
  private readonly logger = new Logger("ExecutionManager");
  private readonly stderrParser = new StderrParser();
  private readonly registryManager: RegistryManager;
  private readonly timeoutManager: SimulationTimeoutManager;
  private readonly fileBuilder: SketchFileBuilder;
  private readonly localCompiler: LocalCompiler;
  private readonly dockerManager: DockerManager;
  private readonly streamHandler: StreamHandler;
  private readonly filesystemHelper: FilesystemHelper;
  private readonly processExecutor: ProcessExecution;
 
  constructor(
    registryManager: RegistryManager,
    timeoutManager: SimulationTimeoutManager,
    fileBuilder: SketchFileBuilder,
    localCompiler: LocalCompiler,
    dockerManager: DockerManager,
    streamHandler: StreamHandler,
    filesystemHelper: FilesystemHelper,
  ) {
    this.registryManager = registryManager;
    this.timeoutManager = timeoutManager;
    this.fileBuilder = fileBuilder;
    this.localCompiler = localCompiler;
    this.dockerManager = dockerManager;
    this.streamHandler = streamHandler;
    this.filesystemHelper = filesystemHelper;
    this.processExecutor = createProcessExecutionPort();
  }
 
  /**
   * Main execution entry point: orchestrates prepare → start → stream → timeout → cleanup
   */
  async runSketch(options: RunSketchOptions, state: ExecutionState): Promise<void> {
    const { code, onOutput, onError, onExit, onCompileError, onPinState, timeoutSec, onIORegistry, onTelemetry, onPinStateBatch } = options;
 
    // Transition to STARTING state
    const canStart = this.transitionTo(state, SimulationState.STARTING);
    Iif (!canStart) {
      this.logger.warn(`runSketch ignored - invalid state: ${state.state}`);
      return;
    }
 
    // Clear pending cleanup for a fresh run
    state.pendingCleanup = false;
 
    // Create and start PinStateBatcher
    state.pinStateBatcher = new PinStateBatcher({
      tickIntervalMs: config.timeouts.batcherTickIntervalMs,
      onBatch: (batch: PinStateBatch) => {
        if (state.messageQueue && this.registryManager.isWaiting()) {
          for (const s of batch.states) {
            state.messageQueue.push({
              type: "pinState",
              data: { pin: s.pin, stateType: s.stateType, value: s.value },
            });
          }
        } else if (onPinStateBatch) {
          onPinStateBatch(batch);
        } else if (onPinState) {
          for (const s of batch.states) {
            onPinState(s.pin, s.stateType, s.value);
          }
        }
      },
    });
    state.pinStateBatcher.start();
    this.registryManager.setPinStateBatcher(state.pinStateBatcher);
 
    // Bind callbacks
    state.onOutputCallback = onOutput;
    state.errorCallback = onError;
    state.pinStateCallback = onPinState || null;
    state.telemetryCallback = onTelemetry || null;
 
    // Initialize run state
    this.initializeRunState(code, onOutput, onIORegistry, timeoutSec, state);
 
    // Create and start SerialOutputBatcher
    state.serialOutputBatcher = new SerialOutputBatcher({
      baudrate: state.baudrate,
      tickIntervalMs: config.timeouts.batcherTickIntervalMs,
      onChunk: (data: string, firstLineIncomplete?: boolean) => {
        Iif (typeof onOutput !== "function") return;
 
        Iif (state.backpressurePaused) {
          setTimeout(() => {
            if (
              state.backpressurePaused &&
              state.serialOutputBatcher &&
              !state.serialOutputBatcher.isOverloaded() &&
              state.state !== SimulationState.PAUSED &&
              state.processController.hasProcess()
            ) {
              this.logger.info("Backpressure relieved, sending SIGCONT");
              state.processController.kill("SIGCONT");
              state.backpressurePaused = false;
            }
          }, 0);
        }
 
        const endsWithNewline = data.endsWith("\n");
        const parts = data.split("\n");
        for (let i = 0; i < parts.length; i++) {
          const isLastPart = i === parts.length - 1;
          Iif (isLastPart && endsWithNewline) {
            break;
          }
          const isComplete = !isLastPart && !(i === 0 && firstLineIncomplete);
          onOutput(parts[i], isComplete);
        }
      },
    });
    state.serialOutputBatcher.start();
    this.registryManager.setSerialOutputBatcher(state.serialOutputBatcher);
 
    try {
      // Prepare environment
      const files = await this.prepareEnvironment(code, state, options.headers);
    state.processKilled = false;
 
      Iif (state.pendingCleanup || state.processKilled || state.state === SimulationState.STOPPED) {
        this.filesystemHelper.markTempDirForCleanup(this.extractFilesystemState(state));
        return;
      }
 
      // Create wrapped callbacks
      const wrapped = createStreamCallbacks(onOutput, onError, onPinState, state, {
        registryManager: this.registryManager,
        logger: this.logger,
      });
 
      // Setup and run simulation
      await this.setupSimulationProcess(files, wrapped, options, state);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      this.logger.error(`Kompilierfehler oder Timeout: ${errorMessage}`);
      if (onCompileError) {
        onCompileError(errorMessage);
      }
      Eif (onExit) {
        onExit(-1);
      }
      state.processController.destroySockets();
      this.filesystemHelper.markTempDirForCleanup(this.extractFilesystemState(state));
    }
  }
 
  /**
   * Initialize run state for a new execution
   */
  private initializeRunState(
    code: string,
    onOutput: (line: string, isComplete?: boolean) => void,
    onIORegistry?: (registry: IOPinRecord[], baudrate: number | undefined, reason?: string) => void,
    timeoutSec?: number,
    state?: ExecutionState,
  ): void {
    Iif (!state) return;
 
    const baudMatch = /Serial\s*\.\s*begin\s*\(\s*(\d+)\s*\)/.exec(code);
    state.baudrate = normalizeBaudrate(
      baudMatch ? Number.parseInt(baudMatch[1]) : 9600,
    );
 
    const executionTimeout = normalizeSimulationTimeout(timeoutSec);
    this.logger.info(
      `🕐 runSketch called with timeoutSec=${timeoutSec}, using executionTimeout=${executionTimeout}s`,
    );
    this.logger.info(`Parsed baudrate: ${state.baudrate}`);
 
    state.pauseStartTime = null;
    state.totalPausedTime = 0;
    this.registryManager.reset();
    this.registryManager.setBaudrate(state.baudrate);
    this.registryManager.enableWaitMode(config.timeouts.registryWaitModeAfterStartMs);
    state.messageQueue = [];
    state.outputBuffer = "";
    state.outputBufferIndex = 0;
    state.isSendingOutput = false;
    state.totalOutputBytes = 0;
    state.outputCollector = new OutputCollector(SANDBOX_CONFIG.maxOutputBytes);
    state.onOutputCallback = onOutput;
    state.ioRegistryCallback = onIORegistry;
  }
 
  /**
   * Prepare environment: write sketch files
   */
  private async prepareEnvironment(
    code: string,
    state: ExecutionState,
    headers: Array<{ name: string; content: string }> = [],
  ): Promise<{ sketchDir: string; sketchFile: string; exeFile: string }> {
    const sketchId = randomUUID();
    const files = await this.fileBuilder.build(code, sketchId, headers);
    state.currentSketchDir = files.sketchDir;
    return files;
  }
 
  /**
   * Perform compilation (local path only; Docker handles internally)
   */
  private async performCompilation(
    sketchFile: string,
    exeFile: string,
    opts: RunSketchOptions,
    state: ExecutionState,
  ): Promise<void> {
    // Delegate to extracted prepare-phase function
    const prepareContext: PrepareContext = {
      localCompiler: this.localCompiler,
      logger: this.logger,
      transitionTo: this.transitionTo.bind(this) as (state: ExecutionState, newState: SimulationState) => boolean,
    };
    await performCompilation(sketchFile, exeFile, opts, state, prepareContext);
  }
 
  /**
   * Setup simulation process: compile and spawn
   */
  private async setupSimulationProcess(
    files: { sketchDir: string; sketchFile: string; exeFile: string },
    callbacks: ExecutionCallbacks,
    opts: RunSketchOptions,
    state: ExecutionState,
  ): Promise<void> {
    // Router-Phase: Decide between Docker and Local execution
    const route = decideExecutionRoute(state);
 
    if (route.useDocker) {
      await this.runDocker(files, callbacks, opts, state);
    I} else if (route.shouldThrowOnNoDocker) {
      throw new Error("Docker sandbox is unavailable; refusing local fallback in production mode");
    } else {
      await this.runLocal(files, callbacks, opts, state);
    }
  }
 
  /**
   * Run in Docker container
   */
  private async runDocker(
    files: { sketchDir: string; sketchFile: string; exeFile: string },
    callbacks: ExecutionCallbacks,
    opts: RunSketchOptions,
    state: ExecutionState,
  ): Promise<void> {
    const executionTimeout = normalizeSimulationTimeout(opts.timeoutSec);
    const containerName = `unosim-sandbox-${randomUUID()}`;
    state.currentContainerName = containerName;
 
    const { onCompileError, onCompileSuccess, onExit } = opts;
 
    // ── Docker compile gating ─────────────────────────────────────────────────
    // Limit the number of simultaneous g++ compilations inside Docker containers
    // to prevent CPU starvation when many students start simulations at once.
    // The slot is released once [[RUNTIME_START]] is detected (compile done) or
    // on any error, so the semaphore only covers the compile phase.
    const queueStartTime = Date.now();
    const releaseSemaphore = await getDockerCompileSemaphore().acquire(() => {
      opts.onCompileQueued?.();
    }, config.timeouts.compileGatekeeperAcquireMs);
    const queueWaitTimeMs = Date.now() - queueStartTime;
    
    // Guard: abort if the simulation was stopped while we were waiting
    Iif (state.processKilled || state.pendingCleanup || state.state === SimulationState.STOPPED) {
      releaseSemaphore();
      return;
    }
 
    // Release wrapper – idempotent, called from compile-phase callbacks or onClose
    let semaphoreReleased = false;
    const releaseOnce = () => {
      if (!semaphoreReleased) {
        semaphoreReleased = true;
        releaseSemaphore();
      }
    };
 
    // Track compile metrics
    const compileStartTime = Date.now();
    let compileTimedOut = false;
    
    // Wrap compile callbacks so the semaphore is released as soon as the
    // compile phase ends (success or error), freeing the slot for the next waiter.
    const wrappedOnCompileSuccess = () => {
      compileMetricsTracker.recordCompileComplete(compileStartTime, queueWaitTimeMs, true, compileTimedOut);
      releaseOnce();
      onCompileSuccess?.();
    };
    const wrappedOnCompileError = (err: string) => {
      compileMetricsTracker.recordCompileComplete(compileStartTime, queueWaitTimeMs, false, compileTimedOut);
      releaseOnce();
      onCompileError?.(err);
    };
 
    try {
      // Start-Phase extrahiert: Docker-Command + Spawn + processStartTime + RUNNING-Transition
      const dockerStartContext: DockerStartContext = {
        processController: state.processController,
        transitionTo: this.transitionTo.bind(this) as TransitionToFn,
      };
      const dockerStartParams: DockerStartParams = {
        sketchDir: files.sketchDir,
        containerName,
      };
      await runDockerStart(dockerStartParams, state, dockerStartContext);
      this.logger.info("🚀 Docker: Compile + Run in single container");
 
      const dockerState: DockerState = {
        isCompilePhase: { value: true },
        compileErrorBuffer: { value: "" },
        compileSuccessSent: { value: false },
        totalOutputBytes: { value: state.totalOutputBytes },
        processStartTime: state.processStartTime,
        stderrFallbackBuffer: state.stderrFallbackBuffer,
        flushTimer: state.flushTimer,
      };
 
      const dockerCallbacks = {
        onOutput: callbacks.onOutput,
        onPinState: callbacks.onPinState ?? (() => {}),
        onError: callbacks.onError,
      };
 
      state.processController.onError((err) => {
        this.logger.error(`Docker process error: ${err.message}`);
        callbacks.onError(`Docker process failed: ${err.message}`);
      });
 
      // Single close handler: state transition + cleanup.
      // Note: compile callbacks, batchers, and onExit are handled exclusively
      // by dockerManager.setupDockerHandlers → handleDockerExit to avoid
      // double invocation (which previously caused a double "stopped" event).
      // releaseOnce() here is a safety net for edge cases where the container
      // dies before emitting any compile output.
      state.processController.onClose((_code) => {
        releaseOnce();
        this.transitionTo(state, SimulationState.STOPPED);
        Iif (state.flushTimer) {
          clearTimeout(state.flushTimer);
          state.flushTimer = null;
        }
        void cleanupDockerContainer(state.currentContainerName, {
          processExecutor: this.processExecutor,
          logger: this.logger,
        });
        this.filesystemHelper.markTempDirForCleanup(this.extractFilesystemState(state));
      });
 
      this.dockerManager.setupDockerHandlers(
        dockerCallbacks,
        dockerState,
        {
        flushBatchers: () => flushBatchers(state),
        flushMessageQueue: () => flushMessageQueue(state),
          getProcessKilled: () => state.processKilled,
          executionTimeout,
        },
        {
          onCompileError: wrappedOnCompileError,
          onCompileSuccess: wrappedOnCompileSuccess,
          onExit,
        },
      );
    } catch (err) {
      const isTimeout = err instanceof Error && err.message.includes("timeout");
      compileMetricsTracker.recordCompileComplete(compileStartTime, queueWaitTimeMs, false, isTimeout);
      releaseOnce();
      this.logger.error(`Docker process spawn failed: ${err instanceof Error ? err.message : String(err)}`);
      this.transitionTo(state, SimulationState.STOPPED);
      state.processController.destroySockets();
      this.filesystemHelper.markTempDirForCleanup(this.extractFilesystemState(state));
      throw err;
    }
  }
 
  /**
   * Run locally (without Docker)
   */
  private async runLocal(
    files: { sketchDir: string; sketchFile: string; exeFile: string },
    callbacks: ExecutionCallbacks,
    opts: RunSketchOptions,
    state: ExecutionState,
  ): Promise<void> {
    const executionTimeout = normalizeSimulationTimeout(opts.timeoutSec);
    const { onCompileError, onExit } = opts;
    
    // Track compile metrics for local execution (no queue wait)
    const queueWaitTimeMs = 0;
    const compileStartTime = Date.now();
    let compileTimedOut = false;
 
    try {
      state.isCompiling = true;
      await this.performCompilation(files.sketchFile, files.exeFile, opts, state);
      state.isCompiling = false;
      
      // Compile success
      compileMetricsTracker.recordCompileComplete(compileStartTime, queueWaitTimeMs, true, compileTimedOut);
 
      if (state.pendingCleanup || state.processKilled || state.state === SimulationState.STOPPED) {
        this.filesystemHelper.markTempDirForCleanup(this.extractFilesystemState(state));
        return;
      }
 
      // Start-Phase extrahiert: Process-Spawn + processStartTime + RUNNING-Transition
      const startContext: LocalStartContext = {
        processController: state.processController,
        transitionTo: this.transitionTo.bind(this) as TransitionToFn,
      };
      await runLocalStart(files.exeFile, state, startContext);
      
      // Stream-Phase: Event-Handler registrieren
      this.setupLocalHandlers(callbacks, onExit, executionTimeout, state);
    } catch (err) {
      state.isCompiling = false;
      const isTimeout = err instanceof Error && err.message.includes("timeout");
      compileMetricsTracker.recordCompileComplete(compileStartTime, queueWaitTimeMs, false, isTimeout);
      if (onCompileError) onCompileError(err instanceof Error ? err.message : String(err));
      Eif (onExit) onExit(-1);
      this.transitionTo(state, SimulationState.STOPPED);
      state.processController.destroySockets();
      this.filesystemHelper.markTempDirForCleanup(this.extractFilesystemState(state));
      throw err;
    }
  }
 
  /**
   * Setup event handlers for local process
   */
  private setupLocalHandlers(
    callbacks: ExecutionCallbacks,
    onExit?: (code: number | null) => void,
    executionTimeout?: number,
    state?: ExecutionState,
  ): void {
    Iif (!state) return;
 
    scheduleExecutionTimeout(this.timeoutManager, executionTimeout, state, callbacks, {
      processExecutor: this.processExecutor,
      logger: this.logger,
    });
 
    state.processController.onStdout((data) => {
      const str = data.toString();
      const withinLimit = state.outputCollector?.append(str) ?? false;
      state.totalOutputBytes = state.outputCollector?.totalBytes ?? state.totalOutputBytes + str.length;
      if (!withinLimit) {
        state.processController.kill("SIGKILL"); // Trigger stop
        callbacks.onError("Output size limit exceeded");
        return;
      }
 
      const lines = str.split(/\r?\n/);
      lines.forEach((line) => {
        if (!line) return;
        const parsed = this.stderrParser.parseStderrLine(line, state.processStartTime);
        delegateParsedLineToStreamHandler(parsed, state, callbacks, {
          registryManager: this.registryManager,
          streamHandler: this.streamHandler,
        });
      });
    });
 
    const useFallbackParser = !state.processController.supportsStderrLineStreaming();
    state.stderrFallbackBuffer = "";
 
    state.processController.onStderr((data) => {
      if (useFallbackParser) {
        handleStderrFallbackData(data, state, callbacks, {
          registryManager: this.registryManager,
          streamHandler: this.streamHandler,
          stderrParser: this.stderrParser,
        });
      }
    });
 
    state.processController.onStderrLine((line) => {
      if (line.length === 0) return;
      const parsed = this.stderrParser.parseStderrLine(line, state.processStartTime);
      delegateParsedLineToStreamHandler(parsed, state, callbacks, {
        registryManager: this.registryManager,
        streamHandler: this.streamHandler,
      });
    });
 
    state.processController.onClose((code) => {
      const wasRunning = state.state === SimulationState.RUNNING;
      this.transitionTo(state, SimulationState.STOPPED);
 
      Iif (state.flushTimer) {
        clearTimeout(state.flushTimer);
        state.flushTimer = null;
      }
 
      Iif (state.stderrFallbackBuffer) {
        const buffered = state.stderrFallbackBuffer;
        state.stderrFallbackBuffer = "";
        if (buffered.trim()) {
          const parsed = this.stderrParser.parseStderrLine(buffered, state.processStartTime);
          delegateParsedLineToStreamHandler(parsed, state, callbacks, {
            registryManager: this.registryManager,
            streamHandler: this.streamHandler,
          });
        }
      }
 
      flushMessageQueue(state);
 
      Eif (wasRunning) {
        flushBatchers(state);
        Eif (state.serialOutputBatcher) {
          state.serialOutputBatcher.destroy();
          state.serialOutputBatcher = null;
        }
        Eif (state.pinStateBatcher) {
          state.pinStateBatcher.destroy();
          state.pinStateBatcher = null;
        }
      }
 
      Iif (state.ioRegistryCallback) {
        const finalRegistry = this.registryManager.getRegistry();
        if (finalRegistry.length > 0) {
          state.ioRegistryCallback([...finalRegistry], state.baudrate, "process-exit");
        }
      }
 
      Eif (!state.processKilled && onExit) onExit(code);
      this.filesystemHelper.markTempDirForCleanup(this.extractFilesystemState(state));
    });
  }
 
  /**
   * State transition (delegated from runner)
   */
  private transitionTo(state: ExecutionState, newState: SimulationState): boolean {
    if (!canTransition(state.state, newState)) return false;
    state.state = newState;
    return true;
  }
 
  /**
   * Extract filesystem state for delegation
   */
  private extractFilesystemState(state: ExecutionState) {
    return {
      currentSketchDir: state.currentSketchDir,
      isCompiling: state.isCompiling,
      pendingCleanup: state.pendingCleanup,
      cleanupRetries: new Map(),
      currentRegistryFile: null,
    };
  }
}