Evaluating Code Models on Complex Algorithms and State Consistency
Passing sample cases is not the same as being production-ready. This article presents a practical framework for evaluating enhanced-reasoning and lightweight code models on time-dependent shortest paths and event-log replay tasks, with emphasis on hidden constraints, Pareto-optimal states, idempotency, deterministic ordering, snapshots, complexity, and independent verification. It also outlines testing and deployment strategies for building reproducible, auditable model evaluation pipelines.
When models in the same family are released in both a reasoning-focused version and a lightweight version optimized for cost and latency, a common evaluation mistake is to treat “passes the samples” as equivalent to “ready for engineering use.”
Complex algorithm problems and event-replay problems belong to a different class of tasks. Their specifications often contain many implicit constraints. Correctness depends not only on the main control flow, but also on waiting rules, idempotency semantics, tie-breaking, very large integers, determinism, and output behavior. An implementation may look structurally sound yet be completely wrong because it deviates from the specification in one boundary case.
The key to evaluating code-model capability is therefore not whether the model can produce code that looks plausible. A reliable evaluation should determine whether the model can identify invariants, discover hidden conditions, provide a complexity argument, and use tests to demonstrate that the implementation conforms to the specification.
1. Define Correctness Before Comparing Model Strength
For code models, evaluation should be divided into five dimensions:
- Semantic correctness: Does the implementation strictly follow the input and output definitions? This includes tie-breaking priorities, empty input, single-node cases, unreachable states, duplicate keys, and missing objects.
- Boundary coverage: Does it proactively handle large integers, period values of 1, zero cost, parallel edges, identical start and end nodes, equal timestamps, and repeated idempotency keys in a log?
- Complexity and resource usage: Can it run at the target scale? Does it avoid floating-point arithmetic when integers are required, placing an (O(n)) operation inside a loop, uncontrolled recursion depth, or excessive memory usage?
- Determinism and reproducibility: Does the same input always produce exactly the same state and path? Are ties resolved explicitly when sorting keys or objective values are equal?
- Explanation and validation: Can the model describe invariants, complexity, failure boundaries, and test cases instead of submitting unexplained code?
When comparing a reasoning-enhanced model with a lightweight model, the evaluation should not simply conclude that one is universally stronger. Results should be reported by task family, including:
- Main-flow generation
- Boundary-condition detection
- Complexity proofs
- Fault localization
- Test generation
- Bug fixing
- Latency and cost
A reasoning-focused model may perform better on problems involving multiple interacting constraints, but that advantage is not guaranteed on every task. A lightweight model is often more suitable for low-risk completion, boilerplate code, log classification, simple refactoring, and test scaffolding.
A dependable engineering workflow is usually a combination of lightweight acceleration, reasoning-model review for high-risk logic, and an independent verifier. A single generated response should not be deployed directly.
2. Complex Algorithm Task: Time-Dependent Shortest Paths with Periodic Availability
Consider a directed graph with nodes numbered from 0 to (n-1). Each edge contains:
[
(u, v, phase, period, duration, cost)
]
Suppose the current arrival time at node (u) is (T). The edge can be used only when:
[
depart + phase
]
is divisible by period. If departure is not currently possible, the traveler may wait until the next valid departure time. Traversing the edge reaches (v) at:
[
depart + duration
]
and adds cost to the total cost.
The required result is a triple:
- The earliest arrival time
- The minimum cost among paths that arrive at that earliest time
- The lexicographically smallest node path among paths that are optimal in both arrival time and cost
If the destination is unreachable, the result is empty. The graph may contain hundreds of thousands of nodes and edges, while times, costs, periods, and phases may also be very large.
The Core Transition Function
The most important abstraction is the time-dependent edge transition. Given an arrival time (T), the valid departure remainder is:
[
r = (-phase) \bmod period
]
The waiting time is:
[
wait = (r - T \bmod period + period) \bmod period
]
Equivalently:
[
depart = T + \bigl(period - ((T + phase) \bmod period)\bigr) \bmod period
]
and:
[
arrive = depart + duration
]
All calculations must use integer arithmetic. If the programming language handles negative remainders differently from the mathematical modulo operation, the result must be normalized explicitly. Floating-point arithmetic is unsafe, and 32-bit integer assumptions may cause overflow.
The waiting and arrival functions are nondecreasing. Starting earlier and traversing the same edge cannot result in a later arrival, because the next valid departure time is nondecreasing as the input arrival time increases. This property allows the earliest-arrival component to be handled with a time-dependent label-setting algorithm.
However, that is only the first step. The problem must not be simplified into an ordinary static shortest-path problem.
Hidden Issue 1: Waiting Can Absorb Intermediate Delays
A label that arrives later at an intermediate node but has a lower cost may eventually arrive at the destination at the same time as an earlier, more expensive label.
For example, suppose two routes lead from the source to an intermediate node (u):
- Route A reaches (u) at time 1 with cost 100.
- Route B reaches (u) at time 6 with cost 1.
The edge from (u) to the destination (t) can depart only at time 10 and takes one time unit. Both routes therefore reach (t) at time 11, but Route B has the lower total cost.
If an algorithm retains only the earliest-arriving label at (u), it discards Route B and eventually reports the wrong cost. A single best pair per node is therefore unsafe. Candidate labels should at least preserve Pareto-optimal states, including labels that arrive later but cost less.
Hidden Issue 2: Lexicographic Paths Are Not Additive Weights
Lexicographic path comparison cannot simply be encoded as another additive edge weight. Lexicographic order compares node sequences element by element; it is not equivalent to summing a numeric value along the path.
After the earliest arrival time (T^) and minimum cost (C^) have been determined, there may still be multiple optimal paths. The implementation must identify states capable of achieving ((T^, C^)), then select the lexicographically smallest node sequence.
A robust approach is:
- Compute (T^*).
- Use reverse constraints to calculate, for each node, the latest time at which it may depart while still reaching the destination by (T^*).
- Run a multi-label search within the feasible region, applying dominance pruning.
- Recover the lexicographically smallest path by backtracking from the destination or greedily selecting the smallest next node that can still complete the same optimal objective.
A single parent pointer is insufficient because multiple equally optimal paths may diverge at intermediate nodes.
Hidden Issue 3: The Case Where s == t
If a zero-edge path is allowed, then:
- Earliest arrival time is
start_time - Cost is 0
- Path is
[s]
If the specification requires at least one edge, that rule must be stated explicitly. Many incorrect implementations fail because this case is left undefined.
Hidden Issue 4: Parallel Edges and period == 1
Parallel edges cannot be merged merely because they share the same destination. They may have different phases, periods, durations, and costs.
An edge with a higher cost but an earlier valid departure may reach an intermediate node first and then wait, eventually tying another edge at the destination. Removing either edge prematurely can change the result.
When period == 1, the waiting time is always zero. This is a useful test for validating the modulo formula. When cost == 0, multiple equivalent paths may exist, so both cost and lexicographic order must be applied as tie-breakers.
Hidden Issue 5: Paths, Cycles, and Output Semantics
If the graph contains zero-cost cycles and waiting can absorb some of the time differences introduced by those cycles, an optimal path under the earliest-arrival and minimum-cost criteria may not be simple.
If repeated nodes are allowed, the specification must define:
- Whether simple paths are required
- Whether the number of edges is bounded
- How lexicographic comparison works when one path is a prefix of another
- Whether parallel edges affect path representation
Without these definitions, model outputs cannot be compared fairly. In some cases, the output size itself may become uncontrolled.
Verification Strategy
For small random graphs, use bounded-depth enumeration as a reference implementation. The test set should include waiting, parallel edges, zero-cost edges, s == t, and unreachable destinations.
For large graphs, check important invariants:
- Every reached node has an earliest time that can be derived from a valid predecessor relaxation.
- Every candidate path uses a legal departure time on every edge.
- No lower-cost label has been incorrectly discarded among labels with the same earliest arrival time.
It is also useful to construct targeted “later but cheaper” graphs and verify whether the implementation incorrectly keeps only one shortest-path label per node.
3. Event Replay: Idempotency, Ordering, Permissions, and Snapshots
The second representative task is reconstructing state from an unordered event log.
Each event contains a timestamp, actor, idempotency key, operation type, and payload. The system maintains an owner and value for each object.
Events must be replayed in ascending order by:
[
(ts, actor, op_id)
]
For the same actor, only the first occurrence of a given idempotency key in that sorted order takes effect. Later duplicates are ignored.
The operations have the following semantics:
addcreates an object only if it does not already exist.moveanddeletetake effect only when the current owner matches the actor.snapshotrecords the state of specified objects at that moment. A missing object is recorded as empty.
This may look like simple simulation, but it has a high error rate in practice.
Correct Processing Order
A correct implementation should follow these steps:
- Establish a global deterministic order by sorting on timestamp, actor, and idempotency key. If completely identical sort keys are possible, use the original input index as the final tie-breaker.
- Maintain a set of consumed idempotency keys for each actor. The namespace is
(actor, op_id), so different actors may use the same key independently. - Maintain an object-state table keyed by object ID. Each value contains the owner and object value.
- Process events in sorted order. Before handling an event, check whether the actor has already consumed the idempotency key. If so, skip the event. Otherwise, mark the key as consumed before executing the operation.
- An
addthat finds an existing object, amoverejected for lack of permission, and adeletethat finds no object should all still consume the idempotency key. Idempotency applies to processing the request, not only to state-changing operations. - A
snapshotdoes not modify object state, but it is still subject to idempotency rules. The snapshot must copy the current value rather than retaining a reference that could later be modified. - Snapshot results should be emitted in log-processing order. The order and duplicate entries in the payload’s ID list should be preserved if the specification permits them. A missing ID should produce an empty result, and an object deleted before a snapshot should also be treated as missing.
Language-independent pseudocode can be written as follows:
function reconcile(events):ordered = stable_sort(events, key = (ts, actor, op_id, input_index))seen = map from actor to set of op_idobjects = map from id to {owner, value}snapshots = []for e in ordered:if e.op_id in seen[e.actor]:continueseen[e.actor].add(e.op_id)if e.kind == "add":if e.id not in objects:objects[e.id] = {owner: e.actor,value: deep_copy(e.value)}else if e.kind == "move":if e.id in objects and objects[e.id].owner == e.actor:objects[e.id].owner = e.new_ownerelse if e.kind == "delete":if e.id in objects and objects[e.id].owner == e.actor:delete objects[e.id]else if e.kind == "snapshot":row = []for id in e.ids:if id in objects:row.append({id: id,owner: objects[id].owner,value: deep_copy(objects[id].value)})else:row.append(null)snapshots.append({label: e.label,data: row})else:reject_or_ignore_according_to_spec(e.kind)// The op_id has already been consumedreturn snapshots
Common Failure Modes
Important hidden cases include:
- Duplicate keys must be checked after sorting, not in original input order.
- Different actors may reuse the same idempotency key.
- An
addfor an existing object should ignore only the creation attempt; it must not overwrite the current owner or value. - The behavior of moving an object to its current owner should be explicitly defined.
- Deleting an object and adding the same ID later should create a new object.
- Snapshots require deep copies. Otherwise, later moves or deletes can corrupt previously recorded results.
- Sorting fields must support deterministic comparison. If input types can vary, they must be normalized.
- Large logs may require external sorting or batched merging rather than loading all events into memory.
- Snapshot output may be very large, so its complexity is necessarily at least linear in the total output size. A full-table scan should not replace indexed lookup by object ID.
Useful randomized properties include:
- Repeating the same event for the same actor and idempotency key after its first occurrence must not change the final state.
- The same key used by different actors should be processed independently.
- Any
moveordeletefrom a non-owner must be rejected. - A snapshot must remain unchanged after later operations.
- A snapshot after deletion should show the object as missing.
- Events with the same timestamp must be ordered deterministically using the remaining sort keys.
Encoding these properties as automated checks is more effective than inspecting a few sample outputs. It exposes assumptions that may remain hidden in model-generated code.
4. Evaluation and Deployment for Engineering Use
Evaluation should record failure categories rather than only reporting pass rates. Common categories include:
- Missing hidden constraints
- Incorrect tie-breaking priority
- Integer overflow
- Improper floating-point use
- Confusing input order with specification order
- Failure to copy snapshots
- Treating a no-op as a reason not to consume an idempotency key
- Applying single-label shortest-path logic to a multi-label time-dependent graph
- Incorrect lexicographic path reconstruction
- Complexity that exceeds the required limits
Once failures are classified, it becomes possible to identify the actual boundary between the reasoning-enhanced and lightweight models.
A reliable evaluation pipeline should contain four layers:
- Public samples to verify the basic workflow.
- Hidden boundary tests covering
period == 1, zero cost, parallel edges, identical start and destination, repeated idempotency keys, permission failures, and delete-then-recreate behavior. - Random differential testing that compares small inputs against an independent reference implementation or exhaustive enumerator.
- Large-scale stress testing for runtime, memory, determinism, and consistency across repeated executions.
For algorithmic tasks, require the model to provide both a complexity analysis and an explanation of counterexamples. For event-replay tasks, require explicit state invariants and the idempotency-key consumption order. The ability to identify ambiguities and ask for clarification is itself an important engineering capability.
In deployment, lightweight models can handle low-risk completion, log-field extraction, test-template generation, and simple refactoring to reduce latency and cost. Reasoning-focused models are better suited to multi-constraint design, boundary analysis, complex defect localization, and counterexample generation.
Regardless of the model used, independent static analysis, unit tests, property-based tests, and code review should remain part of the control process.
Large-scale replay and offline evaluation typically require sorting, state storage, log aggregation, and result archiving. General-purpose compute, object storage, and logging services from platforms such as Baidu AI Cloud can be used to build a traceable evaluation pipeline that archives model outputs, test results, failure categories, and version differences over time. This creates a regression-friendly and auditable engineering loop.
Only such a process turns model evaluation from a one-time subjective impression into a reproducible, measurable, and continuously improvable technical result.
