Author: YuxiaAI Editorial

  • Why Your MySQL Count Query Returns 1 Instead of the Real Total

    Your export says the total is 1, even when you know there are more rows. Start with the count SQL. If it looks like SELECT COUNT(*) FROM (SELECT COUNT(*) FROM ...) AS counted, the outer query is counting the one summary row the inner query produced. The number inside that row never gets read.

    Run the exact count statement directly before editing it. If SQL returns the right value but PHP shows 1, check the result-reading code. mysqli_result::$num_rows counts result rows, and a count query normally has just one. Read the value in its first column instead. Below, we're dealing with the other case: the SQL total itself is wrong.

    For an ungrouped detail export, you can usually use the inner count directly. With GROUP BY, though, that outer count might belong there. First decide what a row in the exported file is supposed to represent.

    Download the complete SQL examples. The file includes all eight cases with expected results. Each statement contains its own synthetic fixture and runs on MySQL 8.0+ without creating tables or changing data.

    We found this pattern while reviewing a real PHP export builder. It tried to replace the selected columns with COUNT(1), then wrapped the result in COUNT(*). There was another catch: the replacement expected spaces where the SQL template had line breaks.

    That's an awkward bug to untangle. A failed replacement can leave you with a meaningful total. Fix the replacement so it matches, and you may suddenly get 1.

    We'll use invented table names and three synthetic rows to show why. They reproduce the counting pattern, without company data. This is a code review and a worked example, rather than a report of a fix deployed to production.

    Start with three rows and two orders

    Here's a small fixture you can reason through without a large export file. It uses a MySQL 8.0+ common table expression, so there's no table to create:

    WITH items AS (
        SELECT 1 AS item_id, 10 AS order_id
        UNION ALL SELECT 2, 10
        UNION ALL SELECT 3, 20
    )
    SELECT COUNT(*) AS total
    FROM items;

    The result is 3. There are three item rows, belonging to two orders.

    For the snippets below, keep the same WITH items AS (...) fixture and swap the final SELECT. The CTE exists for one statement only. If you'd rather run each case as-is, the download includes the fixture in every statement.

    Now wrap a count inside another count:

    SELECT COUNT(*) AS total
    FROM (
        SELECT COUNT(*) AS item_count
        FROM items
    ) AS counted;

    You get 1. Start inside the query and follow what each layer receives:

    1. The inner query produces one row whose item_count value is 3.
    2. The outer query receives that one row.
    3. The outer COUNT(*) returns 1.

    The outer query doesn't read item_count. It just counts the row containing it. Swapping COUNT(*) for COUNT(1) won't help; you'll still have the extra aggregation layer.

    MySQL documents that an aggregate query without GROUP BY treats its input as one group, and that COUNT(*) counts rows. Those two rules explain this result. See the MySQL aggregate-function reference.

    The empty-result test catches it immediately

    Try a filter that matches nothing:

    SELECT COUNT(*) AS total
    FROM items
    WHERE order_id = 99;

    This correctly returns 0. But the nested version still returns 1:

    SELECT COUNT(*) AS total
    FROM (
        SELECT COUNT(*) AS item_count
        FROM items
        WHERE order_id = 99
    ) AS counted;

    Zero is still a value inside a row. The inner count produces that row, and the outer count happily counts it.

    This is why we'd include an empty filter in the regression checks. A wrong total of 1 can look perfectly reasonable if you test with one record. It's harder to miss when the answer should be zero.

    When the outer count should stay

    Now suppose you want one exported row per order. There are two orders in our fixture, so the total should be 2—even though there are three item rows.

    SELECT COUNT(*) AS total
    FROM (
        SELECT order_id
        FROM items
        GROUP BY order_id
    ) AS grouped;

    Here the inner query returns two rows, one per order. The outer query counts exactly what we want.

    Remove the wrapper and use SELECT COUNT(*) FROM items GROUP BY order_id, and you'll get two values: 2 and 1. If the export worker reads only the first, it could use the size of one group as the total for the job.

    Keep any HAVING condition that controls which groups are exported:

    SELECT COUNT(*) AS total
    FROM (
        SELECT order_id
        FROM items
        GROUP BY order_id
        HAVING COUNT(*) >= 2
    ) AS grouped;

    This returns 1, because only order 10 has at least two item rows. Dropping HAVING would count groups the export excludes.

    An outer count also works for a distinct result:

    SELECT COUNT(*) AS total
    FROM (
        SELECT DISTINCT order_id
        FROM items
    ) AS distinct_orders;

    That gives 2 as well. If your export removes duplicates across several columns, keep that same combination in the inner query. Counting distinct orders instead could give you a different answer.

    These subqueries are derived tables: the outer query operates on the rows they return. MySQL's derived-table documentation explains the syntax and alias requirement.

    Why a harmless formatting change can reveal the bug

    Back to the PHP builder. It performed two steps in a row: replace the selected columns with a count, then wrap the SQL in another count. This is a simplified version:

    $countSql = preg_replace(
        '/SELECT concat([\s\S]*) FROM returns/',
        'SELECT count(1) FROM returns',
        $exportSql
    );
    $totalSql = "SELECT COUNT(*) FROM ($countSql) AS counted";

    Notice the literal space after SELECT and before FROM. The template we reviewed had a newline after SELECT. In our synthetic PHP check, the multiline version made zero replacements; a matching single-line version made one.

    When the replacement doesn't match, the wrapper counts rows from the original detail query. When it does match, an ungrouped inner count produces one summary row. The wrapper then counts that row and gives you 1.

    So getting the regex to match is only half the job. Check the SQL it leaves behind before deciding the bug is fixed.

    For diagnosing existing regex-based builders, capture the replacement count:

    $countSql = preg_replace(
        $pattern,
        $replacement,
        $exportSql,
        -1,
        $replacements
    );
    if ($countSql === null || $replacements !== 1) {
        throw new RuntimeException('Count-query rewrite did not match once');
    }

    This catches an error or an unexpected number of replacements. It does not prove that the generated SQL counts the right thing. PHP's preg_replace documentation describes the replacement-count argument and return values.

    For an export builder we're maintaining, we'd build the data and count queries explicitly from shared filters and parameters. Asking a broad regex to understand nested queries, comments, aliases, and string literals leaves plenty of room for surprises.

    Choose the count that matches your export

    Before touching the count, finish this sentence: ‘One exported row represents…’ Then choose the shape that counts that thing.

    One exported row represents Count approach Check carefully
    One joined detail row Direct COUNT(*) over the same joins and filters A one-to-many join can multiply rows
    One order regardless of item count Count the grouped or distinct order result Detail-row count is a different total
    One group meeting an aggregate condition Count a subquery retaining GROUP BY and HAVING Removing HAVING changes eligibility
    One distinct combination of fields Count the exact distinct result Distinct on just one field can undercount

    Use the same filters and bound values in both queries. A status, date, or existence condition that's missing from the total can make an otherwise sensible count disagree with the file. Bind input values as parameters.

    For a total across all matching rows, exclude batch LIMIT and OFFSET. Keep a limit only when the product deliberately exports a capped result and the total is supposed to describe that cap. Similarly, remove ordering only when it does not affect which rows are selected.

    Wrapping the original result query is a useful starting point for checking correctness. Once the numbers agree, look at the execution plan with representative data. These three-row examples tell us about the count's meaning; they don't tell us how fast your production export will run.

    Verify the generated SQL and its consumer

    We ran the synthetic cases on MySQL 8.4. The checks covered direct and nested counts, empty results, grouped results, HAVING, and DISTINCT.

    Case Expected total
    Three detail rows 3
    Count wrapped around an ungrouped count 1
    Empty detail result, direct count 0
    Empty detail result, nested count 1
    Two grouped orders 2
    Empty grouped result 0
    Groups with at least two items 1
    Distinct order IDs 2

    Check both ends of your own count path: the SQL sent to the database and the value the worker reads back. The consumer we inspected takes the first column of the first row when a count query is supplied. For that path, the query needs to return one scalar total.

    Then compare that total with the file for a small, fixed dataset. Include no matches, several items for one order, and several orders. If records can change between counting and exporting, check snapshot consistency too; a correct count query can't hold changing data still.

    A query can run without error and still count the wrong thing. Compare its total with the rows your export actually contains.

    If your count query fails with an ambiguous-column error instead of returning the wrong number, see our related investigation of an unqualified GROUP BY column. That article follows column ownership through a generated export query; this one focuses on the shape of the total itself.

    If the total is correct but rows disappear later, follow the batch through the formatter and writer in the CSV export completeness investigation.

  • Internal Chat App Features Checklist: Lessons From a Four-Platform Pilot

    A work chat app can send messages successfully and still get in people's way. Can I find the right colleague? Did they notice my reply? Where's that file someone sent last week? Those were the kinds of questions behind our pilot feedback.

    We spent roughly a month building and trialing our own internal chat tool, using Codex during development. PC, Android, iOS, and a WeChat mini program all ran during the trial. Colleagues already used WeCom, so that was the comparison we had to live up to.

    Their requests were very practical: group chats, clearer unread indicators, search across conversations, and a way to copy an order number from an image. We worked through the feedback and added features gradually.

    Below, we've turned those requests into checks another team can use. The feedback is from our trial. The suggested tests are a checklist for you to run, rather than a claim that we've already passed every one.

    Download the editable checklist: 24 acceptance scenarios (CSV).

    The short checklist

    Before people depend on the tool for everyday work, can they do these things?

    • Find colleagues by department or role and reach the right group.
    • Tell which conversations need attention.
    • Understand what happens when they mention someone or quote a message.
    • Control notifications without accidentally missing important replies.
    • Find old messages and attachments across conversations.
    • Reuse information through copying, forwarding, saving, or text extraction.
    • Use voice and attachments where those fit their work.
    • Complete their tasks on the devices they actually use.
    • Recognize when a conversation needs to move to an external channel.

    A check mark beside ‘search’ won't tell you much. Ask someone to find a document when they can't remember who sent it. That's where you find out whether search is helping.

    1. Start with the people employees need to reach

    Our feedback included requests for group chats and a directory organized by department and role. Sales colleagues also needed access on PC.

    These requests fit together. You can't send a useful message until you can find the right person and open the app where you're actually working.

    For the directory, try something harder than a familiar name. Ask a trial user to find the person responsible for a function when they know the department but not the name. If they have to ask around first, find out what the directory was missing.

    For groups, agree on the membership rules first. Who creates one? Who can add people? How much history can a new member see? Your company may answer these differently from ours; the point is to make the choices explicit.

    Colleagues also raised the problem of contacting people outside the company and having to involve sales. That's a separate decision from improving the message screen. You may still need another channel for external conversations.

    Explain that before a wider rollout. People need to know what belongs in the new tool, what stays elsewhere, and how to move information between them. Otherwise they find the boundary in the middle of a job.

    Suggested test: Give a trial user a fictional request involving another department. Ask them to find the intended recipient, start the conversation, and explain what they would do if it required an external contact.

    2. Decide what “needs attention” means

    Colleagues asked for clearer read and unread indicators, message counts, group read receipts, and the ability to mute conversations.

    You could turn these into four separate interface tickets. We'd also look at them together: when work is waiting for someone, what does the app actually tell them?

    Unread, read, and done aren't interchangeable. Someone can open a chat and still have a task to finish. Several people can read a group message without anyone taking responsibility for it.

    Be clear about what each indicator means. If the badge counts unread messages, don't make it look like a task counter. For read receipts, decide what triggers one and who sees it.

    Muting needs the same care. Does it suppress all notifications, or do direct mentions still alert the recipient? Does the unread badge remain? There is no single policy that suits every team, but the behavior should be deliberate and understandable.

    Suggested test: Use two test accounts. Send ordinary messages and a direct mention into a muted group, then record the badge, in-app alert, and device notification separately. Compare the results with your intended policy.

    3. Treat quotes and mentions as different interactions

    Two requests caught our attention. Colleagues wanted to click an avatar to mention someone. They also said a quoted reply could get missed: quoting alone didn't give the original author a special alert, so people still needed to add a mention.

    There was a smaller snag in the reply itself. After choosing a message to quote, the user still had to click the input box before they could type.

    It's a tiny extra step, but it's right in the middle of answering someone.

    When reviewing a quote feature, ask two questions:

    • Does it preserve the context the recipient needs?
    • Does it get the intended person's attention?

    A quote can preserve the context and still fail to notify the person you want. If that's how your app works, give people an obvious way to direct the reply.

    Try the next keystroke too. After selecting a quote, can you start typing straight away? Can you see that you've selected the right message, and cancel it if you haven't?

    Suggested test: In a group with three test accounts, quote a message with and without an explicit mention. Check who receives an alert and whether opening it leads to enough conversation context to understand the reply.

    4. Make old information retrievable

    Our colleagues asked for search across conversations and filters for images, files, and dates. They also wanted favorites for pictures, videos, and files, plus ways to copy and forward longer conversations.

    People remember different bits of the same file: roughly when it arrived, what type it was, a phrase beside it, or that they saved it. Give them a few ways back instead of requiring the one detail they've forgotten.

    Start with a few concrete questions:

    • Can I find a file if I cannot remember which conversation contains it?
    • Can I narrow results to a date range?
    • Can I open the surrounding conversation to understand what a result refers to?
    • Can I get back to an item I deliberately saved?

    Check search with accounts that have different access. Results and previews should follow the same conversation permissions as the messages themselves. A preview shouldn't reveal something the account can't open.

    Forwarding needs its own check. When someone sends a long exchange to a colleague, can the recipient tell what was originally said and what's a new comment? Decide how much attribution and context to keep.

    Suggested test: Place synthetic files in several test conversations. Ask a user to find one using only its approximate date and file type, then explain the surrounding discussion. Record where they get stuck.

    5. Let people use the information inside attachments

    One request was to copy text from an image, such as an order number. Others involved selecting multiple pictures and videos to send, and allowing automatic replies to include an image or a file.

    “Supports attachments” hides quite a lot of work.

    Seeing an image and using the text inside it are different tasks. If someone needs an order number, being able to copy it can save retyping. Sending several files together solves another small but repetitive job.

    For text extraction, check the copied value against the image. Use made-up identifiers with characters that are easy to confuse. People need a way to catch a wrong character before it becomes a lookup for the wrong order.

    For batch sending, try a partial failure as well as a successful upload. Can the sender see which file failed and what to retry? This is a test we'd add, rather than a failure we're claiming happened in our trial.

    If an automatic reply sends a file, who replaces it when it goes out of date? A convenient reply can keep circulating an old document just as efficiently as the right one.

    Suggested test: Send a small set of test images and videos between the relevant clients. Check what arrives, in what order, and how an interrupted upload is presented to the sender.

    6. Give voice, announcements, and saved items a clear job

    Voice messages, speech-to-text, internal announcements, work labels, and favorites all appeared in the feedback.

    Before adding another button, give each feature a job you can describe.

    Voice and text fit different moments. Speaking may suit the sender while the recipient needs to read quietly. Keep a transcript tied to its recording so an unclear phrase can be checked.

    An announcement needs a defined audience and a place where people can find it later. If acknowledgment matters, make that a separate decision rather than assuming that opening the message proves someone has acted on it.

    Labels and favorites also need understandable scope. Are they personal organizing tools or shared team information? Can another person see them? What happens when a saved attachment is no longer available?

    Suggested test: Ask a user to save an attachment, leave the conversation, and find it again. Then ask them to explain whether the saved item or label is visible to anyone else. Their answer will show whether the interface communicates its scope.

    7. Test a complete task across clients

    All four clients ran during our trial. That still leaves the job of checking each feature across them.

    We'd test the whole task. Someone sends a photo from a phone; a colleague opens it on PC. Someone reads a message on one device; what happens to the unread state on the other? That's closer to daily use than checking each screen on its own.

    Use a small matrix with a sender client, a recipient client, an action, and the expected result. Include:

    • Sending and opening an attachment.
    • Reading a message and checking the other device's unread state.
    • Opening a mention or quote notification.
    • Finding an old file and returning to its conversation.
    • Resuming after losing connectivity.

    The screens don't have to be identical. What matters is whether the people on each end can finish the task and understand any differences.

    How to choose the first release

    You don't have to finish the entire wish list before a trial. We built and tried ours at the same time, working through feedback as it came in.

    For your own planning, separate requests into three groups:

    • Needed to complete essential work: a missing capability prevents a role from doing a necessary task.
    • Needed to reduce repeated friction: the task is possible, but people keep searching, retyping, or repeating steps.
    • Useful extensions: the capability adds convenience or supports a less frequent task.

    These are planning categories you can use, rather than our historical release order. Priorities depend on the role. PC access becomes essential pretty quickly if someone needs it throughout their working day.

    Use the downloadable checklist to record the expected behavior, the platforms to test, and the evidence behind a result. Every row starts as Not assessed. Change that only after checking the behavior on the relevant clients.

    The feedback we could work with was specific: help me notice the reply, find the file, copy the number, or reach the right person. Each request gives you something to build and a task you can ask someone to try.

    Continue the series

  • Which Work Requests Should an AI Agent Answer, Act On, or Escalate?

    ‘Can you move this delivery to Friday?’ The sentence is simple. Doing it might mean checking capacity, confirming the address, finding the right approver, and changing a business record. A helpful-sounding reply doesn't get the delivery moved.

    Use the automation decision worksheet to compare a process fix, a fixed workflow, AI assistance, an agent, or a human decision for a specific request. The worked examples below show how to choose.

    When we looked at work conversations, we followed the people replying as well as the people asking. What kept landing with them, and what did they have to do? Three groups helped us sort it out: answers, authorized actions, and decisions that needed a person's judgment.

    That gives you a shortlist to investigate. Before turning a request into an assistant, you still need to know where its information comes from, what it's allowed to do, and how you'll tell it worked.

    Some repeated requests might disappear with a process change. Others could be useful agent tasks while a bigger redesign waits. We're considering agents as a next step; we haven't measured the effect of either approach in this analysis.

    Start by being precise about who handled the request

    The reply is the part you can see in chat. The actual work may happen in an order system, on the phone, or with another team.

    For our first pass, we used fairly simple rules. In customer-service chats, we looked for the first staff reply after a question. In internal chats, we preferred a reply from the person mentioned, within a defined window, then fell back to the first reply from someone else.

    That finds a likely responder. It doesn't necessarily find the person who finished the job. ‘On it’ is an acknowledgment; forwarding a request passes it along. You need another piece of evidence to call the issue resolved.

    Our trial feedback made this especially clear. Colleagues wanted to mention someone by tapping an avatar, and said quoted replies were easy to miss without a special alert. The person addressed, the person notified, and the person replying might all be different. Nearby messages alone can't sort that out.

    Keep a note of how you matched each reply. A direct answer with matching context is easier to trust than the next message in a crowded group. If you can find the later business event showing what changed, add it. Otherwise leave the outcome open.

    No visible reply isn't an AI success, either. Someone may have called, an assistant may have answered, or the question may have been missed. We'd need to check before giving any of those cases a success label.

    Classify the requested outcome

    Topic labels help find similar requests, but they do not specify the authority or workflow needed to complete them. Consider three invented questions about a return:

    Request Work required Initial classification
    “Has the return been received?” Look up a relevant, current status Answer
    “Please arrange pickup for the approved return.” Create an authorized pickup request Act
    “Will you waive the return fee?” Decide whether to grant an exception Human judgment

    They're all about returns, but the work is different. ‘Build a returns assistant’ still leaves a lot of its job undefined.

    People also put several requests in one message: ‘Where is the driver, and can you move the delivery if they're late?’ One part needs information; the other asks for a conditional change. Keep both. A classifier that stops at its first matching label will miss half the job.

    Decide whether the task needs an agent at all

    Calling something an action doesn't mean it needs an agent. If the inputs and steps are already clear, a form or ordinary workflow may handle it perfectly well.

    Download the automation decision worksheet (CSV). Its six illustrative rows separate the requested outcome from the proposed implementation. They are planning examples, not deployed systems or measured automation results.

    Start with these questions:

    1. Is the difficulty caused by missing information, unclear ownership, or an awkward process? Fixing that may remove the request altogether.
    2. Are the inputs and next steps sufficiently defined? A form or rule-based workflow may be enough.
    3. Is one step about interpreting language, such as extracting a request from a message? A bounded AI step may help while the workflow keeps control.
    4. Must the system choose its next investigation step based on what it finds? That is a candidate for an agent, provided its tools, limits, and checks are defined.
    5. Does the decision require authority the system has not been given? Keep that decision with the responsible person; assistance can prepare the evidence.

    You can mix these approaches. A fixed workflow might collect the request, use AI to interpret a message, then send an exception to a person. One useful AI step doesn't require handing it control of the whole process.

    Work through one request before scoring a backlog

    Take a synthetic request: “Can you move this delivery to Friday?” A high repetition count makes it worth investigating, but does not tell us how to implement it.

    What you learn Candidate approach What still needs checking
    Eligible dates and all rules are already explicit A change form and fixed workflow Access, current eligibility, and confirmation
    The message is free text, but the change process is fixed AI extracts the requested date; the workflow validates it Ambiguous dates and requester confirmation
    An investigation must adapt across several sources A bounded agent prepares options Permitted tools, stopping conditions, and source conflicts
    The change needs a discretionary exception A person decides, with evidence prepared for them Who has authority and how the decision is recorded

    Don't let a confident label fill in a missing rule. Which Friday? Is the requested slot still open? Give the workflow a way to stop and ask when it doesn't have enough to proceed.

    For an action, write down the exact change, who approves it, what must still be true before execution, and how you'll confirm the result. If the order changes while approval is waiting, check it again. An old approval may no longer describe the action you're about to take.

    For an answer, write down the source, who can access it, how fresh it needs to be, and what to do when it's missing. Just because the lookup works doesn't mean every requester should see the result.

    Make the pilot decision explicit

    There isn't an automatic readiness score in the worksheet. If the source is unknown, authority is missing, or nobody can verify the outcome, the candidate needs more work—however attractive its potential savings look.

    Mark a candidate Needs clarification while a required dependency is unresolved. Once those dependencies are understood, define a limited test with clear success and failure cases. Include incomplete inputs, conflicting records, repeat requests, and an unavailable service where relevant.

    Count the work people still have to do: prepare data, review answers, fix mistakes, and handle exceptions. A quick generated reply can leave quite a bit of work after it.

    At that point, you have something a developer can work with: one task, an approach, the dependencies to resolve, and a result you can check. You may also discover that the simpler option is enough.

    For an answer, specify the evidence it needs

    An answer candidate should have a known source, a clear interpretation, and access appropriate to the person asking.

    For a shipment update, look up the right order and the latest relevant event. A dispatch record supports ‘it was dispatched.’ It doesn't tell you the driver is nearby. The assistant needs to stop where the evidence stops.

    Decide up front what happens when information is missing or contradictory. For example, the assistant might explain that it can't verify the current position and send the request to someone who can. Put that behavior beside the source, freshness, and access requirements in the review record.

    When you test the answer, read past the pleasant wording. Did it use the right record? Was the requester allowed to see it? Did the answer match the source, including the gaps?

    For an action, define when it is allowed

    An action candidate changes something. The surrounding conditions matter as much as the instruction.

    For the delivery change, a workflow could find the order, confirm the date, check options, and show the proposed change for approval. Check eligibility again immediately before applying it. The warehouse may have moved on while someone was reading the proposal.

    Then check what actually happened. ‘Request accepted’ and ‘delivery changed’ can be different states. The assistant should report the one the business system confirms and explain how to follow up if it's still pending.

    Also plan for the person who sends the same message again because nothing seemed to happen. The workflow needs to recognize a change that's already pending or complete before creating another one.

    For each candidate action, write down:

    • The object and fields that may change.
    • Who may request and approve the change.
    • The business conditions that must hold when it is committed.
    • What identifies a repeated request.
    • What confirms success, failure, or a pending result.
    • Who handles an exception the workflow cannot resolve.

    These are the requirements we'd work through before a pilot. The classifier's action label is the beginning of that work; it doesn't mean the service and approval flow are already there.

    For human judgment, reduce the preparation work

    A disputed delivery, a concession, or a commitment outside normal policy may need a person's decision. An assistant can still do useful preparation.

    For example, an assistant could collect the order timeline, identify the relevant policy, summarize conflicting accounts, and list the missing facts. A responsible person would then make the decision.

    Keep the sources available to the reviewer. ‘The customer says it arrived damaged’ is different from ‘it arrived damaged.’ Shortening the summary shouldn't erase who made the claim.

    Human judgment is also contextual. An organization might define a narrow policy for a small, routine concession and allow an authorized workflow to apply it. That depends on an explicit policy and implementation. A general label such as “refund” cannot establish the boundary by itself.

    Combine the responder and requester views

    From the requester's side, we ask whether the need could have been spotted earlier. From the responder's side, we ask what can happen next. Keeping both questions stops a useful alert from turning into an action nobody authorized.

    The following examples are hypothetical:

    How the need appears Answer Authorized action Human judgment
    Observable from existing state Send a relevant shipment update Create a follow-up task under a defined overdue-work rule Flag a possible policy exception for a manager
    Requires someone's intent Answer a question about a product Prepare a requested delivery-date change Review a request for compensation

    An overdue-work rule may detect that attention is needed while leaving the eventual decision to a person. Conversely, a customer can initiate a routine change that an authorized workflow can carry out. Both distinctions matter when deciding what to build.

    Review the classifications before presenting a percentage

    Our first pass used rules and keywords. They helped sort a review queue, but broad labels can make the opportunity look cleaner than it is. ‘Please handle this’ might conceal a dispute. One message might contain two requests and receive only one label.

    A stronger review samples each category, including ambiguous and unassigned cases. Reviewers should see enough surrounding conversation to identify the actual request. Record disagreements and why they happened: missing context, an unclear policy, conflicting source data, or a weak classification rule.

    Be clear about what you're counting. Order-linked questions, questions with a matched reply, customer-service messages, and all company conversations are different sets. A percentage from one doesn't automatically describe the others.

    Keep track of how far each candidate has got. Looking suitable is one step. Finding the data and authority, getting a prototype to work, and checking it in a supervised pilot are later steps. Don't roll all of that into a single automation percentage.

    Choose a pilot you can inspect

    We'd start with one request type, perhaps an order-status lookup. Write down what a correct answer needs, when it should say it doesn't know, and who takes over. Then check whether the person asking actually got what they needed to continue.

    For an action pilot, keep human review while checking whether proposals identify the right object, preserve the intended change, and produce a confirmed result. Record repeated requests, failed attempts, and cases that required correction as well as successful ones.

    Where you can, measure the work left for people. Reply counts miss investigation, coordination, approvals, and exceptions. Saving some typing may be worthwhile, but it isn't the whole workload.

    For each candidate, you should be able to name the source, the permitted action or person making the decision, and the result you'll check. That's a concrete enough starting point to build a pilot and learn from it.

    Continue the series

    For a practical employee pilot, see what a personal AI assistant can do at work: useful tasks, the value to look for, and the setup we are preparing.

    Once a request needs a person, see how to prepare a customer support handoff with AI, including current requests, revised promises, evidence and clear ownership.

  • How to Find Proactive Alerts in Work Chat Questions

    ‘Has this been scheduled yet?’ Somebody has stopped to ask, and somebody else has to look it up. If the answer is already in a system, it's worth asking why those two people need to do that work again.

    Use the recurring-question worksheet to group follow-ups into cases, review their causes, and choose a small improvement to test. Worked examples appear below.

    When we reviewed company conversations, we looked at what made people ask for help. Some questions needed a new decision or preference. Others were about something the business might already have been able to see.

    Take an address change. You can make the process easier, but someone still has to tell you the new address. Here we're looking at the other kind of question: could the need for attention have been spotted before the message arrived?

    The method below is how we'd choose and test those checks. The examples are invented, and the suggested checks aren't a list of features already running in our company.

    Begin with the work behind the question

    Common phrases are a useful place to start. Then read around them. What was the person trying to get done, and why did they need to ask?

    Suppose a salesperson asks whether an order has shipped. Maybe they can't see the shipping status. Maybe it's buried three screens deep. Maybe it just says ‘processing,’ or they've learned not to trust it. The same question can hide several different problems.

    Sending an alert won't fix a status nobody trusts. You might just distribute the confusion faster. Sometimes the useful change is explaining the status properly.

    Try writing the need in one sentence: ‘The requester needs to know whether the order will leave in time for the agreed delivery window.’ You can investigate that. ‘We get lots of shipping questions’ doesn't give you much to build yet.

    Keep a question record and a case record

    Our first extraction looked for order references in messages. That helped us find related work, but one order could produce several follow-ups about the same delay—or several entirely different requests.

    A useful analysis should retain both levels:

    • A question record preserves the request, time, channel, sender role, and surrounding context.
    • A case record groups questions that concern the same underlying issue, while preserving their sequence.

    So don't group everything by order number and stop there. A delivery update and an address change are different needs. Three follow-ups about the same scheduling delay belong together, but keep all three visible: someone was interrupted each time.

    We'd keep both numbers. Cases tell you how often the problem turns up. Follow-ups give you a feel for the coordination around it. You'll still need to look at the actual work to estimate effort.

    Turn a week of questions into a reviewable worksheet

    Choose a time window and the channels you're allowed to review. Keep the unclear messages too. If you include only order-linked questions, say so in the report; otherwise it's easy to mistake that slice for the whole workload.

    Download the recurring-question worksheet (CSV). It contains five synthetic message records to demonstrate grouping. Replace those examples with records you are authorized to use; the suggested actions are not results from our company.

    Give each question its own row, then use a shared case ID for related questions. That way you can see repeated interruptions without counting the same unresolved problem as several different problems.

    Consider this invented sequence:

    Message Case Why it belongs there
    Has the delivery been assigned? CASE-A Opens a question about assignment
    Any update on that assignment? CASE-A Follows up on the same unresolved need
    Who can check the assignment? CASE-A Another follow-up, with an ownership question
    Please change the delivery address CASE-B A new requested outcome, even if it concerns the same order

    Four questions, two cases. Three interruptions came from the first case; the other needs something new from the requester. If we put all of them in one order-number bucket, that difference disappears.

    For each case, note the task, what was known before the first question, who replied, who owned it if you can tell, and what would count as done. If all you have is ‘I'll check,’ leave the outcome open.

    When you compare weeks, use the same inclusion rules. Fewer follow-ups might be encouraging, but check whether there were fewer cases—or whether everyone moved to another chat. The worksheet helps you ask those questions.

    Choose a response to the pattern

    Once you see a repeated pattern, go back to what made people ask. Then choose one small change to try:

    • Information is accurate but hard to find: improve the status page, wording, search, or access path.
    • A recorded state needs timely attention: specify a notification or overdue check, including its owner and exceptions.
    • The next step depends on a new preference: make the request or change process easier to complete.
    • A colleague must interpret ambiguous context: consider AI assistance, with the original evidence available for review.
    • The cause is still unclear: collect the missing context before choosing a fix.

    Three people asking about a delivery could mean the status is hidden, stale, or genuinely worrying. Counting the phrase won't tell you which. Read the cases.

    Before building the fix, show a handful of cases to the people doing the work. Ask whether your explanation fits and what you've missed. That's usually a more useful conversation than asking them which parts of support they'd like to automate.

    Ask what was knowable before the message

    Be careful with hindsight. After an order is resolved, the problem can look obvious. What matters for an early check is what the system knew before anyone asked.

    For each question, inspect the preceding state and use one of three review labels:

    Label Evidence needed Illustrative example
    Detectable from available state A relevant record, a reliable time or condition, and someone who needs the information An unassigned delivery has passed its agreed assignment deadline
    Requires new human intent A preference, request, or decision that has not yet been recorded A customer wants delivery moved to a different address
    Insufficient evidence Missing context, unreliable state, or an ambiguous request An order reference posted with no explanation

    Our initial rules used yes or no. We'd add the third category before making a deployment decision, so a vague message doesn't quietly become a confident automation candidate.

    A bare order number might mean colleagues share a familiar routine. You still need the surrounding messages to find out what it is. ‘Please hurry’ is similar: it tells you someone is concerned, but doesn't identify the system event an alert should detect.

    Separate visibility from notification

    Once you know the information is available, decide how people should get it. These are the options we'd consider:

    Make the information easier to find. If people repeatedly ask for an ordinary status, a clearer order page or direct status link may be sufficient. The person can check when it matters to them.

    In our trial, colleagues asked for cross-chat search, file and date filters, and copying order numbers from images. They were trying to get back to information already in the conversations. Those requests gave us product work to do, but didn't mean an alert was the right answer.

    Send an update when something changes. If someone is waiting on a particular transition, a relevant update can save a lookup. The recipient and the event must be specific enough that the message arrives for a reason.

    Escalate when something fails to happen. An order that should have progressed but has not may need a timed check and an owner who can investigate. The check depends on an explicit expectation, including valid exceptions.

    Help with the next step. When the information is available but the existing workflow still requires someone to look it up and reply, an agent might perform that specific task. It should identify the record, use the same source the team trusts, and report uncertainty. This can be useful even before a larger process change is made.

    The same topic can need more than one of these. A delivery page can show current status, while a separate overdue check alerts the person responsible for a missed milestone.

    Write the alert specification before choosing the AI

    Consider an invented case: an approved order is awaiting assignment, and the agreed assignment deadline has passed. A useful alert specification would answer the following questions:

    Decision Example specification
    What condition matters? Approved order, assignment missing, deadline passed
    What source supports it? Order state and assignment record, checked for freshness
    Which cases are excluded? Canceled orders, recorded customer holds, and explicitly rescheduled work
    Who receives it? The team responsible for assignment, with an escalation owner
    What can they do? Open the relevant record, assign it, or record a valid hold
    How are repeats handled? Keep one open alert for the same incident; update it when the state changes
    What closes it? Assignment completed or an authorized exception recorded

    If the records already contain the fields you need, a straightforward rule may do the detection. AI could help with ambiguous wording or a useful explanation afterward. Start with the job, then decide where it needs AI.

    Keep the explanation close to the record. ‘No assignment is recorded’ says what you found. ‘Dispatch forgot the order’ adds a cause—and blame—that you haven't established.

    Test against the clock, including late data

    Historical review is a useful place to start. Pick past cases and ask whether the proposed check would have fired before the actual question. Use the information available at that earlier time wherever possible.

    Sometimes you only have today's database state. That may tell you where an order ended up without showing what was visible when someone asked. Mark the historical check as uncertain instead of counting it as a detection that would have worked.

    Data arrival time also matters. A delivery might have occurred while its confirmation reached the system later. Decide how stale a source can be before an alert becomes untrustworthy, and how the alert should explain that uncertainty.

    Before sending alerts to people, try recording them quietly for review. Ask the responsible team which ones were useful, late, already known, or wrong. Include ordinary cases too; the check needs to know when to stay quiet.

    Measure the help, not just the messages

    Fewer questions sounds good. It can mean people found what they needed. It can also mean they gave up on that channel. Look at the cases before celebrating the number.

    For a small pilot, we'd track case volume, follow-ups per case, unresolved delays, and how long it took to turn a useful signal into action. For an alert, ask the recipient whether it arrived in time and gave them something they could do.

    Keep the definition of a case and the observation window consistent. Compare similar work periods and examine changes in order volume or the kinds of cases arriving. Raw chat totals cannot account for those differences.

    Keep the first pilot small enough to read its mistakes. One recurring question with a clear owner gives you a manageable place to learn.

    Then come back to the original question. If people still ask ‘Has this been scheduled yet?’, find out why. Was the alert late? Did it go to the wrong person? Or did the status still leave them guessing? Each answer points to a different next change.

    Continue the series

  • Why We Built an Internal Chat Tool to Find Workflow Problems

    Sometimes a work message is just an order number. That's all the sender types. Someone else still has to recognize it, open the right system, work out what needs checking, and reply. A very short message can leave quite a long to-do list behind it.

    We wanted to understand that hidden work in our building materials supply business. We were using WeCom for internal communication, but our setup didn't give us direct access to the conversation data we needed to investigate it.

    So we used Codex to help build a chat tool for our company. For roughly a month, we developed it while colleagues tried it in real work. A WeChat mini program, PC, Android, and iOS clients all ran during the trial. With conversation records available to examine, we could look from both sides: what made someone ask for help, and what did the person replying have to do next?

    The information we needed was scattered through conversations

    Orders, delivery plans, and changes already had records in our business systems. What we wanted from chat was the part those records don't always show: where someone had to stop and ask another person for help.

    An order can have a status on its record and still leave a salesperson asking what that status means. We wanted to see those moments too.

    Consider this illustrative exchange, written for this article rather than taken from an employee's messages:

    “Any update on order A104?”
    “It's waiting for a delivery slot. I'll check with dispatch.”

    That reply helps with the order. It also leaves us with a few questions. Could the salesperson see the status? Did the status explain what was waiting? Was anyone clearly responsible for the next step? Had it already taken too long?

    Two messages won't answer all of that. But they give you somewhere to look. We wanted to do that across conversations, rather than depend on whichever frustrating incident someone happened to remember.

    Why we chose to build

    For us, access to the messages was the immediate obstacle. Another company may have different arrangements with WeCom; this was the constraint in our own setup.

    Building our own tool gave us conversation records in a system we controlled. Codex helped with development. Whether that trade-off makes sense elsewhere depends on the systems a company already has and the communication it needs to support.

    A month is a short time to build across four clients, especially while people are already using them. Every client adds another place where a conversation can feel awkward or behave differently. Codex helped us develop the software; colleagues still had to decide whether it was usable during their day.

    The hardest part was the comparison with WeCom. Colleagues already knew how a work chat app ought to behave. Our reason for building one was conversation analysis, but that didn't make an awkward reply box any less awkward for the person using it.

    What colleagues actually asked for

    The feedback wasn't abstract. People needed group chats, a directory by department and role, clear read and unread indicators, message counts, and a way to mute a busy conversation. Sales colleagues needed PC access. These were the things that decided whether the tool fitted into their working day.

    Some requests were about tiny moments that can derail a reply. You couldn't tap an avatar to mention someone. Quoting a message didn't give its author a special alert, so they could miss the reply unless you added a mention. Colleagues also wanted group read status and an easier way to reply to a quote.

    Then there were attachments and history: voice messages and transcripts, copying an order number from an image, sending several photos or videos together, saving useful files, and searching across chats by file type or date. People also asked for long-message forwarding, announcements, work labels, and automatic replies with images or files. We worked through the requests in stages. The list wasn't a single release, and we haven't measured the workload saved by each change.

    One request went beyond the interface. Colleagues couldn't use the tool to contact people outside the company, so they had to go through sales. That belongs in a replacement decision just as much as unread badges do: which conversations will the new tool actually cover?

    Our colleagues' first test was pretty straightforward: can I find the right person, send what they need, and notice their reply? We had to work on that before the records could tell us much about everyday work. If conversations keep moving elsewhere, the analysis loses part of the picture.

    Before building anything similar, check what you can get from your existing tools. If the records and context are already available, you can start the analysis there. Running your own chat service comes with an ongoing job attached.

    Messages still need to reach the right people, history needs to be recoverable, and access has to follow company rules. The interesting analysis only helps if the ordinary communication works.

    This is where adoption becomes part of the data problem. If someone has to stop and think which device or app to use, a conversation may split across tools. Features for analysts won't, on their own, make colleagues switch.

    A message needs its surroundings

    The analysis we developed used records from internal conversations and customer-service conversations. Keeping those sources distinct mattered. An employee coordinating with a colleague and a customer asking for an update can use similar words while facing different access and responsibility boundaries.

    For the analysis, the useful record contained more than the message body:

    Information What it helps establish
    Sender and role Whether a message is a request, staff reply, or system notice
    Conversation reference Which surrounding messages might explain it
    Time The order of the exchange and possible response delay
    Business reference Which order or other work item may be involved
    Mention or reply context Who was being asked and who appeared to respond

    We started with messages containing order references. That made it easier to connect a question to a piece of work. It also narrowed what we were looking at: plenty of company problems never arrive with an order number attached.

    An order number gives you somewhere to start, but it doesn't tell you what the person wants. They might need a status update, an address change, or help with a disputed charge. The next step is different in each case.

    Before reviewing conversations, agree which ones are in scope, who can read them, what staff are told, and how long you keep them. Owning the app doesn't answer those questions for you. Usually you can explain the workflow problem without publishing someone's messages or turning the analysis into an employee ranking.

    Looking from the person asking

    First, we looked at the person asking. What had interrupted their work enough that they needed somebody else's help?

    Some requests supply information the system could not reasonably know beforehand. A customer changes their plans. A salesperson asks for a different delivery arrangement. Somebody needs an exception. A person has to express that intent.

    Other requests ask for information that may already exist in a system: whether something has been scheduled, whether a shipment has moved, or whether a process has stalled. Those are candidates for better visibility, timely updates, or automated checks.

    Those differences point to different fixes. A scheduling request may need a simpler form. A repeated status question may need a clearer order page. An overdue task may need an alert to the person who can move it along.

    My own fairly conservative estimate is that roughly four in five of the problems we collected might have a process-improvement route. That's a judgment, not a measured success rate. It doesn't mean we need a big redesign for every issue, either. Building agents for some repeated requests is a next step: a reliable lookup or an approved action could help while the broader process stays as it is.

    There's a useful reality check here: could the system have known enough before the message arrived? Spotting the words ‘late delivery’ afterward doesn't tell you whether a reliable delivery event or promised time was available earlier.

    Looking from the person replying

    Then we looked at the people replying. We associated questions with likely responders and reviewed the work showing up in those exchanges.

    For customer-service conversations, a first staff reply was one signal. In internal conversations, the rules preferred a reply from the person mentioned in the request, with a first-other-reply fallback within a defined window.

    That's a starting point. ‘I'll check’ tells you someone replied, but the work may continue in another system, over the phone, or with somebody else. In a busy group, the next message may even belong to a different conversation.

    We could use the result to find clusters of repeated lookups and routine actions, then inspect the messages behind them. We couldn't use it to rank productivity or decide that an entire role could be automated.

    From this side, we classified possible assistance into three types: answering from available information, carrying out an authorized business action, and referring a decision that needs human judgment. A short reply can conceal any of the three.

    The two lenses need each other

    Take an illustrative request to move a delivery to a different day. The customer must supply the desired change, so the system cannot eliminate the need to express that preference. An assistant might still help check available dates and prepare the change for approval.

    Now take an order that has remained unassigned beyond an agreed deadline. If the relevant state and deadline are reliable, the system might detect the delay before somebody asks about it. The resolution could still require a person to make a scheduling decision.

    So we kept asking two questions: could we notice the need earlier, and could we do the next step? Sometimes the answer to the first was yes while the second still needed a person.

    That gave us smaller things to work on: a clearer status, a useful alert, an easier request form, or one action an agent could carry out with permission.

    What the analysis can actually support

    Our first classification pass used rules and keywords. That helped organize the review, but some messages stayed ambiguous. An order number alone doesn't tell you the request. ‘Urgent’ can mean a known delay, a new request, or a disagreement nobody has recorded elsewhere.

    Before putting a percentage on automation potential, we'd need a reviewed sample and clear definitions, plus a check that the data and actions really exist. A label is enough to suggest an experiment. It doesn't tell us how much time we'll save.

    That's how I use the estimate: as a reason to look more closely at repeated questions and possible agent tasks.

    We've made the conversations available for analysis and looked at both sides of the exchange. The next useful step is to pick one recurring problem, change something specific, and see what happens.

    We'd start with a question people recognize, information we can trust, and someone who owns the next step. Then come back to the conversation: do people still need to ask, and is the work actually moving?

    Continue the series

  • How to Audit Permissions Across a New Payment Action

    A payment button disappears for an account without permission. Good—but can that account still open the form directly? What about the endpoint that creates the request, or the QR-code page afterward? That's the route we followed through a ‘Request partial payment’ feature.

    With AI helping us read the Git history, we found a later commit adding a dedicated permission for the feature. This is a business-system example with identifying details left out. To find out which staff actually received that permission, we'd also need the deployed role settings.

    The first version borrowed existing permissions

    The earlier version borrowed existing permissions. Opening the form and fetching the QR code required general order-view access. Creating the request needed broader order-payment access, and the button followed that payment permission too.

    Those were permission checks, but they weren't asking quite the same question. Someone who can view an order doesn't necessarily need to start a partial payment. Once the feature becomes a separate business action, its access rule needs to follow that decision.

    The later change followed the whole path

    The later commit added a dedicated part_pay check to the form, create-request endpoint, and QR-code endpoint. It changed the button visibility check too, and the codebase included a permission mapping for the action.

    That gave us a path to review from end to end. The button was one stop on it. Someone might reach a form or result URL directly, so we wanted to see the checks on those routes as well.

    We broke the review into five questions:

    • Button: which permission decides whether staff see the action?
    • Form: does opening the form check the same dedicated permission?
    • Create endpoint: does the server check permission again before changing anything?
    • QR-code endpoint: can someone request the result directly without entering through the button?
    • Permission mapping: is the new permission defined, and which roles actually receive it?

    The source can help answer the first four. For the last one, open the actual role settings too. A permission defined in code doesn't tell you which staff have been granted it.

    We'd be careful about calling the whole flow secure from this one diff. We'd still check alternate routes, actual grants, and whether a QR-code request is tied to the correct record. What we could see here was that these particular routes had moved to the dedicated permission.

    A useful review pattern for new actions

    For another feature that changes money, stock, or customer data, follow the same route through the system:

    1. The page or button that introduces the action.
    2. The form that collects the request.
    3. The server endpoint that performs the action.
    4. Any related download, image, or result endpoint.
    5. The permission mapping and the actual grants used by staff roles.

    This is a useful task to give AI during review: map the routes and show the permission check on each one. Then open every path it lists. It's easy for a neat summary to miss a less obvious result or download endpoint.

    For testing, we'd use one role with permission and one without. Try the form and QR-code URL directly, then through the button. Also check that a rejected create request leaves no payment record behind. We didn't run those live-system tests in this Git review.

    When you add a new action, trace it past the button. The form, the write endpoint, and the result can each have their own route into the feature.

    The same payment feature also produced a different investigation: why an expired link could block a new request. Reviewing the route inventory and the record lifecycle separately made each question easier to verify.

    Turn the route inventory into a test matrix

    Use two test roles on a synthetic order: one with the feature permission and one without it. Give both only the underlying access your application normally requires, and record that setup. Otherwise, a denial caused by missing order access can hide a missing feature check.

    Entry point Without feature permission With feature permission
    Button and direct form URL Button hidden; direct access denied Available when business conditions permit
    Create endpoint Denied; no new payment record Still subject to order and amount validation
    Direct QR-code URL Denied Only the authorized record is accessible

    Repeat the direct requests with a record outside the role’s permitted scope. A feature permission should not erase record-level access rules. The permission worksheet marks every observed result as Not tested until you run it. These are acceptance criteria to verify, not a claim that the historical change passed them.

  • How to Investigate an Unqualified GROUP BY Column in a SQL Export

    One export fix changed a single column in a GROUP BY clause. The commit message just said ‘Fix export issue.’ Before the change, the column had no table alias. Afterward, it did. We wanted to know why that tiny edit mattered.

    There wasn't much to go on in the diff, so we followed the query around it: which tables did it join, which table owned the field, and what kind of row was the export supposed to produce?

    We used AI to help read the commit and surrounding query. The example comes from a business system, with identifying details left out. We had the code change, but no linked incident report showing the error users saw or when the fix was deployed.

    Where the line sat

    The line sat in an order export's item-detail branch. That branch grouped by an order ID and an item attribute ID. Several tables were joined, including orders and export details, so the source of each grouping field mattered.

    Before the change, the GROUP BY clause referred to the item attribute ID by its bare column name. After the change, it used the export-detail table's alias. A simplified illustration looks like this:

    -- Before
    GROUP BY orders.id, attribute_id
    
    -- After
    GROUP BY orders.id, export_items.attribute_id

    The real code used different table and field names; this example is just a way to show the difference without copying production SQL.

    Why an alias matters

    When several joined tables have a column with the same name, a bare reference can be ambiguous. Even when the database can resolve it today, the next person reading the query has to work out which table you meant. Another join can make that small omission a problem later.

    The alias made that choice explicit: use the field from the export-detail row. For an order with several items or attributes, that's a detail you want to be able to see in the query.

    There are two things to check here. An ambiguous name can make the database reject the query. A query that runs can still group the wrong rows if the key or join relationships are wrong. The alias helps identify the key; you still have to check the output.

    We didn't find a captured failing query or a linked error report in this Git review. So we could explain the change, but couldn't honestly name the exact database error that prompted it.

    The checks that turn a clue into an answer

    If this export were failing in front of us, we'd work through these checks next:

    1. Get the exact SQL generated by the failing export and the database error, if one exists.
    2. Check which joined tables contain the column and whether the unqualified reference was ambiguous in the deployed schema.
    3. Compare row counts and a few representative orders before and after the change. A query that runs can still return the wrong number of rows.
    4. Confirm that the count query used for export progress is built from compatible SQL. An export can appear stuck or show the wrong total even when the data query itself works.

    These are the next checks we'd recommend. We didn't query production data as part of this review.

    What made this worth keeping

    A small diff can be a useful doorway into a bigger query. Here, reading the joins and the item-detail branch explained why the alias belonged there. It also showed us which questions the diff couldn't settle.

    AI can help find the changed line and follow the query around it. To finish the diagnosis, get the generated SQL, any database error, and a before-and-after output comparison. That's what turns a plausible explanation into a checked one.

    If you are writing up a change like this, our Git-to-case-study workflow shows how to keep the code evidence and unanswered questions together in the draft.

    If the query runs but the export total is always 1, see why a MySQL count query returns 1 instead of the real total, with eight runnable examples covering empty results, grouping and distinct rows.

    Run a small example with two different attributes

    The SQL exercise gives the order an attribute of 7 and its two item rows attributes of 101 and 102. Both sources have a column called attribute_id. The unqualified grouping is deliberately ambiguous. Grouping by the item’s attribute produces two groups; grouping by the order’s attribute produces one group containing two rows.

    That last query is useful because it runs successfully. An alias resolves which column you mean, but it can still identify the wrong business key. For an item-level export, check that the output retains both item attributes. The fixture uses MySQL 8.0+ CTEs and only SELECT statements; it creates no tables. Run each statement separately so the deliberate error does not prevent you from trying the other two.

    This exercise illustrates two distinct failure modes. It does not reconstruct the undocumented production error behind the original commit.

  • Why an Expired Payment Link Can Block a New Request

    The old payment link has expired. You try to create a new one, and the system says there's already a request in progress. How can both be true? In the code we reviewed, expiry and the stored request status had drifted apart.

    If you’ve ever had a website insist that something is still active after it stopped working, you know how maddening that feels. The link was done. The database just hadn’t gotten the memo.

    We followed this one through Git history with AI helping us compare revisions. It's a business-system example, with identifying details and real order data left out. The history shows how the code changed; it doesn't tell us whether AI helped write the original fix.

    The rule made sense—until time got involved

    The duplicate check had a sensible job: don't let staff create a second payment request while one is unfinished. When the first link still works, that's exactly the behavior you want.

    The catch was time. The duplicate check read the stored status without checking the request's age. Elsewhere, the system treated a link as expired after 48 hours. Opening that expired link could mark its record invalid. Leave it unopened, though, and the record could keep looking unfinished.

    So the two parts of the system disagreed. One said, “This link has expired.” The other said, “There’s still a payment request in progress.” The second answer won, and the new link never got created.

    What the Git history revealed

    The history filled in the sequence. The partial-payment feature came first, then a dedicated permission check a few days later. About a month after the original change, another commit addressed expired records blocking the next request.

    The permission review is a separate case from this expiration problem. They concern the same feature, but answer different engineering questions.

    We couldn't get that explanation from the messages alone. We had to read the earlier and later code, then follow both the expiry check and the path that creates a request.

    One detail was easy to get wrong: a comment mentioned 15 minutes. That check had been commented out; the active rule was 48 hours. It's worth checking the condition itself before copying a number from a comment into your own fix.

    The fix cleans up the old request before checking for duplicates

    The newer code deals with eligible expired requests for the current order first. If an unfinished request is old enough to expire, it marks it invalid. Then it runs the duplicate check again, so a genuinely active request can still block a second one.

    Both steps sit inside the same transaction. So if a later check rejects the request, or creating it fails, the cleanup rolls back too. That detail matters when you're trying to understand what remains in the database after an unsuccessful attempt.

    The cleanup happens when someone tries to create a request. There isn't a scheduled sweep here clearing every old payment record.

    What still needs testing

    Before treating this as a finished fix in your own system, we'd check a few cases:

    • An expired unfinished request should stop blocking a new one.
    • A recent unfinished request should still prevent a duplicate.
    • If another active request exists, the operation should fail and the transaction should restore any status it changed.
    • If creating the new request fails, the transaction should roll back the cleanup.
    • Simultaneous requests and delayed payment callbacks need a closer look at the surrounding locking and callback logic.

    Those are the tests we'd want to run in a safe environment. This review followed the source code; we didn't run the scenarios against production or verify the deployment date.

    A useful way to investigate “stuck” records

    If you're chasing a similar ‘still in progress’ message, put three things side by side: the status in the database, the expiry condition, and the code that updates the status. Time can run out on a link without anything having written that fact back to its record.

    Then follow the sequence from the old link to the new request:

    1. Find the rule that decides whether the old link is still usable. Read the active condition, not only its comment.
    2. Find the query that blocks duplicate requests. Check whether it reads status, creation time, or both.
    3. List every path that changes the stored status. Ask what happens if the expired link is never opened again.
    4. Inspect the creation transaction. If it marks an old request invalid and a later step fails, determine whether that change rolls back.
    5. Test an expired request, a recent request, and two competing requests in a safe environment. Record the observed result rather than assuming the code covers every timing case.

    AI was useful for finding related commits and following the two paths together. The important part was checking the conditions it found. To find out what users actually experienced after the change, we'd still need deployment records and monitoring.

    Check the stored state after a failed attempt

    For a synthetic test, give one order an expired unfinished request and another active request. The cleanup may invalidate the expired record temporarily, but the active request should reject creation. Under the transaction described above, that rejection rolls the cleanup back. Inspect the stored state after the transaction finishes; a log line from inside it is not enough.

    Starting point Expected committed result
    Expired request only; creation succeeds Old request invalid; one new request created
    Expired request plus active request Creation rejected; cleanup rolled back
    Expired request; creation fails No new request; old status restored by rollback

    These are proposed checks, not newly measured production results. Download the expiry test worksheet to record what your implementation actually does. It also leaves concurrency and delayed callbacks as separate investigations.

  • How to Turn Git Commits Into a Technical Case Study With AI

    A commit called ‘Fix export issue’ isn't much of a story. Someone changed some code, sure—but what went wrong, and why should another developer care? That's where we start when turning Git history into an article.

    We recently used AI to work through a local repository and build a few case studies from related commits. The useful part was following the trail: a message pointed us toward a change, the diff showed what happened, and nearby code sometimes changed the explanation altogether.

    Here's how we did it, including a couple of places where a perfectly confident AI summary could have sent us in the wrong direction.

    Start with a problem a reader might recognize

    We started by looking for changes that raised a question we could actually explain. An expired payment link was blocking the next request. An export fix changed just one line. A payment feature acquired its own permission check. Small changes, but each had something worth following.

    The resulting payment-link investigation, SQL export review, and permission audit show how differently a small code change can read once you follow its surrounding behavior.

    The commit alone wasn't enough. We needed a question: why did an expired link still block a new one? Which table owned that grouping field? Did the permission check protect the routes behind the button? Once we had that, we knew what to read next.

    It also gave us a stopping point. In a large repository, it's very easy to keep following interesting code and forget what the reader came for.

    Read the before and after versions

    For the payment-link case, the commit message pointed to the fix. The earlier code showed a duplicate check based on unfinished status. The newer code handled eligible expired records before repeating that check. A separate expiry function showed the active 48-hour rule.

    Then we found a comment saying the link expired after 15 minutes. The active code said 48 hours; the shorter check had been commented out. Trust the comment and you'd write a tidy explanation with the wrong number in it. We kept the 48-hour rule.

    For the export case, the diff was only one line. We looked at the joins and the branch for item-level detail, then stopped short of claiming a specific database error because the commit did not include one.

    Keep an evidence note beside the draft

    We kept a short note beside each draft: the revision, the relevant code, and anything we still couldn't verify. A Git date tells you when a commit was recorded. It doesn't tell you when the change reached users.

    That note was handy whenever a sentence started sounding a little too certain. We could say the code invalidates eligible expired records before checking for duplicates. We couldn't say customers stopped seeing the problem—we didn't have monitoring or incident records showing that.

    You don't need an elaborate evidence system. Write down the revision and code path behind a claim, what you found there, and what you'd need to check before saying more. For example:

    Question: Why did an expired request block a new one?
    Code evidence: Earlier duplicate check used unfinished status; later code handled eligible expired records first.
    Supported claim: The creation path changed its order of checks.
    Still unknown: Deployment date, production frequency, and user impact.

    This gets especially useful when a feature has been changed several times. A later fix doesn't tell you whether every earlier version was deployed.

    Make the writing human without inventing a human story

    Starting with an architecture tour can make a small, useful story feel like homework. For the payment-link article, we started with the contradiction: the link no longer worked, but the system still wouldn't let anyone create another one.

    We described the database as having ‘not gotten the memo.’ A little personification makes a stale status easier to picture. Then we explained the actual checks, so the phrase had something solid behind it.

    We didn't add customer quotes, invented conversations, or a claim that AI wrote the original fix. The repository gave us enough to explain the code. Anything about the people involved needed another source.

    A compact workflow to reuse

    Want to try it on your own repository? This is the sequence we'd use:

    1. Pick a reader question, not just an interesting commit title.
    2. Group the commits that introduced, adjusted, and fixed the behavior.
    3. Read the relevant code at each revision, including called helpers and surrounding checks.
    4. Record what the code proves and what would need logs, tests, or deployment records.
    5. Draft the article around the reader's problem, then audit each factual sentence against the evidence note.

    Before publishing, read it once more with the code open. Check the comment you quoted. Check whether that date is a commit date or a deployment date. If you recommend a test, make sure the sentence doesn't accidentally imply you've already run it.

    AI helped us find and connect the pieces faster. Deciding which claims belonged in the article still took a careful read. If the repository doesn't answer a question, leave it open—and tell the reader what would answer it.

    Keep the evidence in a reusable record

    A useful record should survive a change of writer. Put the before and after code references beside the claim they support, then leave separate spaces for a test result and a deployment result. An empty field is a useful reminder to investigate; it should not become a confident sentence in the article.

    The engineering review pack includes a blank evidence template. Try filling it in for one commit before drafting. If you cannot name the reader’s question or show the changed behavior, follow the code a little further before choosing the story.

    For a maintenance example with a recorded web-runtime check, see updating PHP in a WordPress Docker deployment.