{"id":"XE-17333","kind":"bounty","visibility":"public","source":"web","source_repo":"","source_ref":"","source_url":"","reporter_id":2799,"title":"Discord mirror re-sends a reply after a failed DB commit — sent-but-unrecorded message, retry posts it twice","area":"other","claimed_tier":"minor","assessed_tier":null,"verdict":"duplicate","duplicate_of":null,"tracked":false,"internal_ref":"","internal_url":"","status":"closed","closed_reason":"duplicate","github_state":"","disclosed_at":null,"award_xe":null,"award_approved":false,"paid_ref":"","created_at":"2026-11-17T12:07:56.524140+00:00","updated_at":"2026-11-23T01:01:14.084469+00:00","source_created_at":null,"told_at":"2026-11-23T01:01:14.122492+00:00","status_changed_at":"2026-11-23T01:01:14.099598+00:00","url":"https://bounty.xe.network/XE-17333","body":"# Discord mirror re-sends a reply after a failed DB commit — sent-but-unrecorded message, retry posts it twice\r\n\r\n## Summary\r\n\r\n`DeskBot.mirror_once` (`desk/bots/discord_bot.py`) sends a queued desk reply into the ticket's Discord thread BEFORE the `db.commit()` that records it as sent. If that commit fails, the `mark_mirrored` update rolls back, the reply stays `mirror == \"queued\"`, and the next mirror pass (every 5 s) sends the same reply a second time. The thread then shows the reply twice, and the desk records only the second send — the first visible message has no desk record at all (no `mirror_ref`, no thread `Message` row).\r\n\r\nThe same ordering defect exists in the same function's state-push half: the closed/reopened line is sent before `mark_state` + `commit`, so a failed commit re-sends the line on the next pass.\r\n\r\n## Target\r\n\r\n- Repo: `xeprotocol/desk` @ `95660dfe25e6004637fc259a1c50c9e408cce5fe` (remote HEAD, verified 2026-11-17).\r\n- Files: `desk/bots/discord_bot.py:276-326` (`mirror_once`), `desk/services/channels.py:271-310` (`queued_replies`, `mark_mirrored`, `writes_to_thread`).\r\n\r\n## Code path\r\n\r\nReply mirror half (`mirror_once`, reply loop):\r\n\r\n```python\r\nasync def mirror_once(self):\r\n    async with session() as db:\r\n        for r, t in await ch.queued_replies(db, PLATFORM):   # mirror == \"queued\"\r\n            th = await self._thread(t.source_ref)\r\n            ...\r\n            try:\r\n                ...\r\n                for part in _chunks(ch.reply_text(self.ctx, t, r)):\r\n                    ...\r\n                    last = await th.send(part, suppress_embeds=True)   # (1) VISIBLE in the thread\r\n                if last is not None:\r\n                    await ch.mark_mirrored(                              # (2) in-memory only\r\n                        self.ctx, db, r, t, message_ref=str(last.id), url=last.jump_url\r\n                    )\r\n            except discord.HTTPException as e:\r\n                await ch.mark_failed(self.ctx, db, r, t, str(e))\r\n            await db.commit()                                            # (3) the only durability\r\n```\r\n\r\n1. The reply is posted into the thread first (`th.send`).\r\n2. `mark_mirrored` sets `r.mirror = \"sent\"`, `r.mirror_ref`, and adds the thread `Message` row — all in the uncommitted session.\r\n3. `db.commit()` is the only step that makes any of it durable. A failure here rolls (2) back entirely, while the Discord message stays visible.\r\n\r\n`queued_replies` selects `Reply.mirror == \"queued\"`, so the rolled-back reply is re-selected on the next pass and sent again with a new Discord message id. `mark_mirrored`'s idempotency cannot collapse the two sends: the dedupe key is the Discord message id (`reply_carried` matches on `source_ref`), and the retry's send has a different id.\r\n\r\nState-push half, same function:\r\n\r\n```python\r\nfor t in await ch.needing_state_push(db, PLATFORM):\r\n    ...\r\n    try:\r\n        if want == \"closed\":\r\n            await th.send(ch.closed_line(self.ctx, t))       # (1) VISIBLE\r\n            await th.edit(archived=True, locked=True)\r\n        else:\r\n            await th.edit(archived=False, locked=False)\r\n            await th.send(f\"Reopened: {t.id} is back with the team.\")\r\n        await ch.mark_state(self.ctx, db, t, want)          # (2) in-memory only\r\n    except discord.HTTPException as e:\r\n        log.warning(\"state push %s: %s\", t.id, e)\r\n    await db.commit()                                        # (3) the only durability\r\n```\r\n\r\nA failed commit rolls `mark_state` back, `channel_state` stays `\"open\"`, `needing_state_push` re-selects the ticket, and the closed line is sent again.\r\n\r\n## Reproduction (executed locally)\r\n\r\nHarness run against the REAL `DeskBot.mirror_once` against a real SQLite database (real `desk.services.channels` functions, real SQLAlchemy models), a stubbed Discord thread, and a session whose first `commit()` raises `RuntimeError(\"simulated DB commit failure\")`. No network, no live services. All checks pass:\r\n\r\n- Pass 1 (commit fails): thread receives exactly 1 send; `reply.mirror` is still `\"queued\"`, `mirror_ref` is `\"\"` — the send is unrecorded.\r\n- Pass 2 (commit succeeds): thread receives a 2nd, byte-identical send; `reply.mirror` becomes `\"sent\"` with `mirror_ref` pointing at the SECOND message. The thread shows the reply twice; the desk records only the 2nd.\r\n- Control (no failure): a fresh queued reply is sent exactly once.\r\n- State-push half: closed line sent once in pass 1 with `channel_state` still `\"open\"` after the failed commit, sent a 2nd time in pass 2, `channel_state` then `\"closed\"`.\r\n\r\n## Impact\r\n\r\nMinor — duplicated desk reply (or closed line) in the support thread plus a desk record that permanently diverges from what thread members see: one visible team message has no desk record, no `mirror_ref`, and no thread `Message` row, so the desk's thread history is missing a message everyone in the thread can see. No funds, credentials, or private data are at risk; the trigger is a transient database failure, not an attacker action. The mirror loop retries every 5 s, so a sustained commit outage duplicates the reply once per pass until the database recovers (bounded by the single queued reply — it stops once one commit succeeds).\r\n\r\n## Suggested fix\r\n\r\nMake the record durable before the retry can re-send: commit `mark_mirrored` / `mark_state` in its own transaction immediately after the send succeeds, and on commit failure do not leave the reply queued for a blind re-send — e.g. record the sent message id out-of-band, or reconcile on the next pass by checking the thread's recent history for an identical reply before re-sending. (Recording the id before sending is impossible — the id only exists after the send — so the fix must be reconcile-or-remember, not reorder.)\r\n\r\n## Distinctness\r\n\r\n- **XE-17287** (new, this cycle) covers the `/answer` slash command: a team member's standard answer posted via `interaction.response.send_message` before `incoming()` + `commit()`. Different code path (manual slash command vs automatic 5 s mirror loop), different record (`Message` row via `add_message` vs `Reply.mirror = \"sent\"` + `mirror_ref` via `mark_mirrored`), different trigger surface (a human re-invoking the command vs the loop's automatic retry), different fix site.\r\n- **XE-13209** (new) covers the state-push closed line re-sent on every pass when the thread EDIT fails — the edit-failure trigger, not the commit-failure trigger, and only the closed line, not the reply mirror. Its own body notes the reopen path does not spam; it never mentions replies or commit failures. The state-push half here is the same line under a different trigger; the reply half is not covered by XE-13209 at all.\r\n- **XE-16854** (GitHub mirror + disclosure double-write: a failed commit after the GitHub post re-posts the reply) is the same root cause on a different channel — precedent that the program treats per-channel instances separately. This is the Discord-mirror instance.\r\n- **XE-16923** (AskModal reports failure after the ticket was committed, retry opens a duplicate ticket) is the ask-flow variant with the opposite order (commit-then-report); different path.\r\n- **XE-9301** (transient fetch failure permanently fails one reply) and **XE-9036** (poison-row stall) are different mirror defects (fetch site / terminal `mark_failed`, malformed ref aborting the pass), not send-before-commit.\r\n- Corpus searches over all 2,869 public tickets: `mirror` (29 titles), `discord` (24), `mark_mirrored` (0), `queued_replies` (0), `commit` (titles checked) — no ticket names the mirror-once reply send-before-commit mechanism. DIVE O (desk commit-then-send sibling sweep, 2026-11-17) listed XE-13209/XE-16854/XE-0782/XE-1167 as the filed instances and missed both this path and XE-17287's `/answer` path.\r\n\r\n## Honest limitations\r\n\r\n- The trigger is a database commit failure, which is transient and uncommon in production; the harness forces it (one simulated failure). The ordering defect is in the shipped code and the failure mode follows directly from it, but no production commit failure was observed.\r\n- The state-push half's observable outcome (duplicate closed line) overlaps XE-13209's; only its trigger (commit failure vs edit failure) is new. The reply half is the distinct new finding.","patch_refs":[],"thread":[{"id":19445,"source":"desk","source_ref":"reply:17122","author":"Joseph Denne","team":true,"body":"Thanks. This is the same finding as an earlier report that is not public, which was filed first; the programme pays the\nfirst verifiable submission, so this one closes as a duplicate. If you believe it is a different\nbug, file a new report that links https://bounty.xe.network/XE-17333 and says what differs; it is read like any other.","created_at":"2026-11-23T01:01:14.084469+00:00"}]}