Evaluating and Optimizing Complex Reasoning in LLMs: Lessons from Code Generation Tasks
This article examines why generating plausible code does not guarantee reliable complex reasoning in large language models. Using two demanding benchmarks—time-dependent shortest paths with multi-objective constraints and deterministic replay of out-of-order event logs—it explains how to build evaluations that are deterministic, verifiable, and explainable. It covers boundary-case design, implementation-independent output validation, failure classification, and practical optimization paths spanning prompt decomposition, algorithm selection, numerical determinism, and automated differential testing. The intended takeaway is a reusable evaluation methodology, a boundary checklist, and a closed optimization loop from prompt design to automated verification.
1. Background: Why “Writing Code” Is Not the Same as “Completing Complex Reasoning”
In real engineering work, teams increasingly rely on AI coding tools to generate algorithm implementations and data processing logic. However, on problems involving multiple layers of constraints, state evolution, and strict output specifications, model performance often diverges sharply. The original cases cover two typical task types: a shortest-path problem with time-window constraints, and an idempotent replay problem for out-of-order event logs. Both share the same characteristics: many constraints, a large state space, dense boundary conditions, and strict output formatting requirements.
These tasks separate models because they test three capabilities at once: formalization (turning natural-language rules into precise logic), algorithm design (choosing the right complexity under scale constraints), and detail execution (handling hidden conditions such as tied optima, lexicographic ordering, and idempotency). A gap in any one of them produces wrong results, and such errors are hard to detect by simply checking whether the code “looks right.”
2. Abstract Modeling of Two High-Difficulty Tasks
2.1 Multi-Objective Shortest Path on a Time-Dependent Graph
The graph is directed, with consecutively numbered nodes. Each edge carries four key attributes: phase, period, duration, and cost. If the current arrival time at a node is T, departure is allowed only when (depart + phase) modulo period equals zero; otherwise, you must wait until the nearest legal moment. The goal is to return a triple: the earliest arrival time, the minimum accumulated cost at that earliest time, and the lexicographically smallest node path. If the destination is unreachable, return a null value.
The difficulty reduces to four points:
- Non-trivial waiting function: a closed-form solution for the minimum non-negative waiting time is required; enumerating time step by step will time out.
- Multi-objective ordering: minimize time first, then cost, then the lexicographic order of the path. The order cannot be swapped.
- Scale pressure: nodes and edges can reach the hundreds of thousands, while periods and durations can reach the billions and the start time can be an extremely large integer, so floating-point error must be avoided.
- Degenerate cases: a period of 1 with zero cost produces many equivalent paths; the start may equal the destination; multi-edges may exist. All of these break naive implementations.
2.2 Deterministic Replay of Out-of-Order Logs
Given a set of out-of-order events, each containing a timestamp, an actor, an idempotency key, an operation type, and a payload. The replay rules are: process in ascending order of (timestamp, actor, idempotency key); ignore subsequent events that repeat an idempotency key under the same actor; apply an add operation only when the object does not exist; apply move and delete operations only when the actor equals the current owner; a snapshot operation records the visible state of a given set of objects, recorded as empty if they do not exist.
The difficulty lies in the following: the sort key must be fully deterministic, idempotency semantics require deduplication up front, permission checks must be based on the “current state” rather than “historical intent,” and snapshots must reflect the true visibility at the moment of replay. Any deviation causes state drift, which is hard to catch through sampling.
3. Evaluation Design: Making Failures Reproducible and Attributable
To assess model capability objectively, the evaluation set must be deterministic, decidable, and explainable.
First, input construction must cover boundaries. Generate cases along dimensions: extremely small and extremely large graphs, period equal to 1 and near the upper bound, all-zero and all-non-zero costs, start equal to destination, multi-edges, fully unreachable cases, and multiple equivalent optimal paths. For log tasks, cover varying degrees of disorder, distributions of repeated idempotency keys, unauthorized operations, empty snapshots, single events, and very large event sets.
Second, output validation must be independent of the implementation. Do not compare only the final value with unit tests; also validate structure (the length and types of the triple), semantics (the time is truly earliest, the cost is truly minimal, the path is truly lexicographically smallest), and consistency (the path endpoints match the start and destination, and the edge sequence is legal). For log tasks, validate state transitions step by step rather than only checking the final state.
Third, failures must be classifiable. Group errors into: rule misunderstanding, insufficient algorithmic complexity, missed boundary cases, output format deviation, and numerical precision issues. Only with clear categories can you tell whether the problem lies in the prompt, in model capability, or in the test design.
A schematic validation framework:
def verify_result(res, n, edges, s, t, start_time):if res is None:return reachable(n, edges, s, t, start_time) is Falsearr, cost, path = resif path[0] != s or path[-1] != t:return False# Validate path legality, time recurrence, cost accumulation, and lexicographic minimalityreturn check_path_legal(path, edges, start_time) and \arr == compute_earliest(n, edges, s, t, start_time) and \cost == min_cost_at(arr) and \path == lexicographically_smallest(arr, cost)
4. Failure Attribution and Optimization Paths
4.1 Prompts and Task Decomposition
Explicitly split complex rules into four parts: “departure condition,” “waiting computation,” “objective ordering,” and “degenerate handling,” and require the model to output a formal definition before writing code. This significantly reduces the rule-misunderstanding rate. For log tasks, require the sort key and deduplication pseudocode first, then the state machine implementation.
4.2 Algorithm Selection and Complexity Constraints
Time-dependent shortest paths typically need a priority-queue search with state, where the state includes the node and the arrival time, plus pruning to avoid state explosion; the waiting time must use a closed-form modulo solution, and advancing second by second is not allowed. Log replay is sorting plus bucketed deduplication plus a linear scan, with overall complexity close to the sorting lower bound.
4.3 Numerical and Determinism Guarantees
Use integer arithmetic for all times and costs, and no floating point; the sort key must define a total order to avoid relying on stability; for equivalent paths, compare lexicographic order explicitly during relaxation instead of relying on traversal order.
4.4 Tooling and External Validation
After the model generates code, automatically invoke a sandbox to run randomized small-data differential testing and output minimized snippets of failing cases. This “generate–execute–feedback–fix” loop turns invisible logic errors into visible test failures. In engineering practice, container platforms, logging services, and monitoring alerts can be combined into an evaluation pipeline that keeps results traceable.
5. Conclusion
Evaluating complex reasoning tasks should not stop at impressions or single-point pass rates; it should establish a system of layered cases, independent validation, and error classification. Time-dependent graph search and out-of-order log replay are two excellent stress tests that expose a model’s real weaknesses in formalization, algorithms, and detail execution. For development teams, the reusable gains are a practical evaluation methodology, a boundary checklist, and an optimization loop that runs from prompt design to automated differential testing. To support large-scale evaluation, general-purpose container and log monitoring capabilities from Baidu AI Cloud can be used to build stable, reproducible evaluation infrastructure.
