AI-Assisted Coding Self-Review: From Code Generation to Risk Annotation

    This article explains how AI-assisted coding can move beyond generating code to annotating engineering risks. It covers what effective risk annotations should include, which issues code self-review should prioritize, how to structure review requests, and how to integrate self-review into a reliable development workflow. The goal is to help developers produce traceable and verifiable engineering deliverables rather than relying on seemingly complete answers.

    1. From Generating Code to Explaining Code Risk

    The most direct use of AI-assisted coding is to generate functions, complete business logic, or modify existing implementations based on natural-language requirements. However, the fact that code can be generated does not mean the code is correct. Valid syntax and successful example runs do not prove that the code satisfies all business constraints, nor do they guarantee reliability under abnormal inputs, concurrent access, or production conditions.

    A more valuable engineering practice is to provide code while also pointing out where potential problems may occur, what conditions may trigger them, what impact they may have, and what verification steps are needed.

    This is a capability goal, not confirmation of a specific product release or feature outcome. In practice, whether an issue can be identified depends on the model’s analytical ability, the provided context, the complexity of the problem itself, and whether independent verification is available. “The model can check its own code” should not be understood as “the code generated by the model no longer needs review.”

    What developers truly need is not an answer that looks complete, but a traceable and verifiable engineering deliverable: what the code implements, what assumptions it depends on, which parts still carry risk, and how to confirm the next step.

    2. What Effective Risk Annotation Should Include

    Saying “there may be a problem here” is only a hint, not a complete defect analysis. A risk annotation that helps developers make decisions should cover at least the following five aspects.

    1. A Clear Problem Location

    The annotation should point to a specific function, branch, data transformation, or resource operation as much as possible, rather than making a vague assessment of an entire file.

    For example, “input handling is not secure enough” has little operational value. In contrast, “the amount conversion logic does not reject inputs with more decimal places than allowed” directly identifies the object to check. When code changes frequently, it is better to use both function names and key logic descriptions instead of relying only on line numbers.

    2. Clear Trigger Conditions

    Many defects do not appear on every run. Empty collections, duplicate requests, dependency timeouts, permission changes, and concurrent writes may all trigger problems that are not easily observed under normal conditions.

    Therefore, a risk description should answer: Under what conditions does it occur? What prerequisites are required? Why does the normal path fail to expose it?

    3. Understandable Impact Scope

    The same code issue may have different priorities in different business contexts. Inaccurate display text and incorrect financial calculations clearly should not be handled with the same standard.

    Impact descriptions should distinguish functional errors, data corruption, sensitive information exposure, service unavailability, and performance degradation. They should also state whether the issue affects a single request, some users, or shared data.

    4. Bounded Fix Recommendations

    A fix should not aim only to eliminate a local error. For example, catching all exceptions and returning a default value may hide real failures. Adding retries may also cause non-idempotent operations to be executed repeatedly.

    Effective recommendations should state applicable conditions, possible side effects, and business constraints that must be preserved.

    5. Executable Verification Methods

    Risk annotation should ultimately lead to tests or checks. If a problem cannot be reproduced or confirmed as fixed, it is difficult to enter a reliable development process.

    “Add more tests” is too broad. A better description is: construct empty inputs, duplicate identifiers, and boundary amounts, then verify rejection behavior, state changes, and returned results respectively.

    3. Key Areas for Code Self-Review

    1. Input Boundaries and Business Constraints

    Input validation is not only type checking. Even if the input type is correct, the value may still violate business rules, such as a negative quantity, an inverted time range, an amount precision beyond the allowed limit, or text length exceeding system constraints.

    Self-review should distinguish two types of constraints:

    • Technical constraints: whether the input can be parsed, whether required fields are missing, and whether the value exceeds the processable range.
    • Business constraints: whether the value is allowed in the current workflow and whether it satisfies state transition conditions.

    If the requirements do not clearly define these rules, the model should list items that need confirmation rather than making decisions on its own.

    2. Numeric Precision and Unit Consistency

    When calculations involve amounts, measurements, or ratios, the representation of numeric values is often more error-prone than the calculation formula itself.

    For example, binary floating-point representation usually cannot precisely express all decimal fractions. Using it directly for monetary calculations may introduce rounding differences. Representing amounts as integers in the smallest currency unit or using an appropriate decimal fixed-point representation is a common solution, but rounding rules, allowed precision, and numeric ranges still need to be clarified.

    Unit issues also need separate checks. Whether timestamps use seconds or milliseconds, and whether distances use meters or kilometers, can cause serious deviations if the two ends of an interface interpret them differently. Code may be syntactically correct but still produce major errors.

    3. Exception Handling and Resource Lifecycle

    The goal of exception handling is not to make errors disappear, but to ensure that failure behavior is understandable, resources can be reclaimed, and state is not silently corrupted.

    Key checks include:

    • Whether failure paths release connections, files, and locks;
    • Whether background tasks continue modifying state after a timeout;
    • Whether errors are swallowed, causing callers to mistakenly treat the operation as successful;
    • Whether logs leak credentials, personal information, or other sensitive content;
    • Whether compensation or rollback is needed after some operations have succeeded.

    These issues often span multiple functions, and checking only one code fragment can easily miss them.

    4. Concurrency, Consistency, and Idempotency

    “Query first, then update” may be correct in a single-threaded example, but it can cause race conditions in a concurrent environment. If multiple requests read the same state at the same time and then write separately, it may lead to overselling inventory, lost counts, or state overwrites.

    Duplicate requests are also a common risk. A network timeout only means the caller did not receive the result; it does not mean the server did not complete the operation. Therefore, when retrying payments, submitting orders, or writing records, idempotency identifiers, deduplication scope, and state consistency need to be considered.

    Self-review cannot focus only on a single method call. It must understand the atomicity and failure boundaries of the entire operation sequence.

    5. Security and Permission Boundaries

    The fact that code can access a piece of data does not mean the current user has permission to access it. Self-review should check whether authentication and authorization are confused, whether only request parameters are checked without verifying resource ownership, and whether external input is directly used in sensitive operations.

    Security checks should not focus only on input filtering. Overly broad default permissions, overly detailed error messages, and sensitive configuration entering logs can also create risks.

    4. Understanding Risk Annotation Through an Illustrative Example

    Suppose we need to implement a settlement function whose inputs include unit price, quantity, and discount ratio. An initial logic might be:

    1. Function calculateAmountDue(unitPrice, quantity, discount):
    2. Return unitPrice × quantity × discount

    This logic is concise, but it implies several unconfirmed assumptions:

    1. The unit price is always non-negative;
    2. The quantity is always a valid integer;
    3. The discount is represented as a ratio between zero and one;
    4. The amount calculation method meets precision requirements;
    5. No additional rounding is required for the result;
    6. There are no taxes, discount caps, or other settlement rules.

    A more qualified analysis does not treat these assumptions as facts. Instead, it lists them as constraints or items that need confirmation.

    For example, it can annotate:

    Risk location: the logic where the discount participates in multiplication.
    Trigger condition: the caller passes the discount as a percentage or passes a value outside the agreed range.
    Possible impact: incorrect amount due calculation.
    Recommendation: clarify the discount representation and enforce range validation at the entry point.
    Verification: cover zero discount, no discount, out-of-bound inputs, and invalid types.

    If the business has confirmed that the smallest currency unit is represented as an integer and the discount is represented by an integer ratio, a further illustrative implementation can be given:

    1. Function calculateAmountDue(unitPriceInMinorUnits, quantity, discountNumerator, discountDenominator):
    2. Validate unitPriceInMinorUnits is a non-negative integer
    3. Validate quantity is an integer within the allowed business range
    4. Validate discountDenominator is greater than zero
    5. Validate discountNumerator is between zero and discountDenominator
    6. subtotal = unitPriceInMinorUnits × quantity
    7. amountDue = calculateWithBusinessRounding(
    8. subtotal × discountNumerator ÷ discountDenominator
    9. )
    10. Return amountDue

    This is still not a complete implementation ready for production. In actual development, integer overflow, error return methods, input sources, and business rules still need to be handled. The value of the example is to show that risk annotation can drive requirement clarification, not just modify a single line of code.

    5. How to Structure a More Effective Self-Review Request

    Asking a model to “check this” is often insufficient. Without context, the analysis may remain at the level of listing common issues or may incorrectly add business assumptions.

    A more effective request should provide the following information:

    • Functional goals and clear invariants;
    • Input, output, and exception return conventions;
    • Data scale, concurrency conditions, and deployment environment;
    • External dependencies and their failure behavior;
    • Related calling code and state change processes;
    • Existing tests and known issues.

    A neutral template can be used as follows:

    1. Please review the following implementation. Do not assume business rules that are not provided.
    2. First, state your understanding of the functional goal.
    3. Then check correctness, input boundaries, exception handling,
    4. concurrency consistency, security, and resource release separately.
    5. For each finding, provide:
    6. problem location, trigger condition, impact, fix recommendation, verification method.
    7. Distinguish:
    8. defects with direct evidence,
    9. risks that require context confirmation,
    10. general improvement suggestions.
    11. If tests have not actually been executed, do not claim that tests have passed.

    This kind of output constraint helps separate conclusions from evidence and makes it easier for developers to filter out issues that truly need attention.

    6. Integrate Self-Review into the Development Loop

    Model analysis should complement other verification methods rather than remain only in a conversation.

    1. Perform Focused Review After Generation or Modification

    First confirm the requirements and implementation, then check around clearly identified risks. For complex tasks, security, concurrency, and exception paths can be reviewed separately to avoid making the review too shallow by including too many goals in one request.

    2. Use Independent Verification Methods

    Static analysis is suitable for finding some syntax, type, and dangerous pattern issues. Unit tests are suitable for verifying local logic. Integration tests are suitable for confirming dependency interactions. Concurrency tests and fault injection can help expose timing and failure-handling issues.

    Problems pointed out by the model must be further confirmed through these methods or manual reasoning. Conversely, the fact that the model did not point out a problem does not constitute proof of safety.

    3. Run Regression Checks After Fixes

    Fixes may change existing behavior. Adding input validation may affect old callers. Adjusting retry strategies may change latency. Modifying lock scope may reduce throughput.

    Therefore, it is necessary to check whether the fix resolves the original problem and confirm that it does not break existing business constraints. Important defects should be turned into long-term regression tests to prevent later changes from reintroducing them.

    4. Keep Necessary Review Records

    For high-risk changes, it can be useful to record the problem description, confirmation basis, handling decision, and verification result. The purpose of the record is not to save every conversation, but to help future maintainers understand why the change was made and which risks are still accepted.

    7. How to Judge Whether Self-Review Is Truly Valuable

    The number of flagged issues should not be the only criterion. A large number of vague warnings can increase review costs and even cause developers to ignore truly serious defects.

    More reasonable evaluation dimensions include:

    • Whether annotations are accurate and can locate real problems;
    • Whether key boundaries and high-impact risks are missed;
    • Whether trigger conditions are clear and reproducible;
    • Whether recommendations fit business constraints;
    • Whether fixes can be independently verified;
    • Whether repeated review and later rework are reduced.

    It is also necessary to be aware of the inherent limitations of self-review. The same analysis process may repeat existing assumptions. When facing an incorrect business description, it may also produce a logically complete but wrong-direction conclusion. Therefore, high-risk code should introduce an independent review perspective rather than relying on self-confirmation after the same generation.

    8. Conclusion: Make Code Delivery Include Verifiable Explanations

    The key shift from code generation to risk annotation in AI-assisted coding is not producing more text, but making assumptions, defects, and verification paths in the implementation visible.

    For individual developers, this approach can help identify missed boundaries and improve understanding and troubleshooting efficiency. For development teams, it can serve as an auxiliary part of code review, promoting structured problem handling, normalized testing, and traceable fixes.

    However, reliability always comes from a complete process: clear requirements, implementation generation, risk identification, independent verification, fix review, and continuous regression. Models can help developers see problems earlier, but they cannot replace engineering evidence. A truly trustworthy deliverable is not only “the code has been written,” but also includes “which risks have been verified and which assumptions still need confirmation.”