MySQL: query_timeout fallback KILL QUERY uses the handshake thread id, which is wrong behind a proxy

Aperta
#547 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

@DongJinNam ci sta già lavorando.

Dal 27/11/2026.

  • #551 di @DongJinNam — aperta

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
70/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
mariadb, mysql, typescript
Ambito
backend, databases

Direzione di ricerca

Start in src/connectors/mysql and trace the timeout handling that captures conn.threadId and calls killQuery; read the connection setup hook that runs SET SESSION max_execution_time for #465. Check how that hook can retrieve SELECT CONNECTION_ID() and preserve the existing fallback if it fails. Done means timeout kills target the backend connection through a handshake terminating proxy; run the MySQL connector tests covering timeout behavior.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Summary

On MySQL, the client-side query_timeout fallback kills the wrong thread when DBHub connects through a proxy that answers the MySQL handshake itself (Teleport database access, and likely any MySQL-protocol proxy that terminates the handshake). KILL QUERY uses conn.threadId, which is the connection id from the proxy's greeting, not the backend's thread id.

Since #465 the server-side max_execution_time covers SELECTs in most cases, so this matters less than it did on 1.4.0. The fallback still exists for the cases #465 describes (limit cleared or raised mid-session), and there it either misses or hits an unrelated session that happens to have the same id.

Where

src/connectors/mysql (1.7.1 dist/mysql-*.js):

const threadId = conn.threadId;
...
} catch (error) {
  if (isClientSideTimeout(error)) {
    isConnectionPoisoned = true;
    await this.killQuery(threadId);   // KILL QUERY ${threadId}
  }

mysql2 fills threadId from the initial handshake packet.

Reproduction

MySQL 8.0.46, a 30-line TCP proxy that rewrites the 4-byte connection id in the server greeting (as a terminating proxy does), DBHub 1.4.0 (before #465, so the fallback is the only mechanism), query_timeout = 5, readonly = true:

SELECT COUNT(*) FROM n a, n b, n c WHERE a.i + b.i + c.i > 0   -- n has 1000 rows

Result:

dbhub answered after 5.1s: "Query inactivity timeout"
processlist 15s later:  id 29 | reader | 22 | executing | SELECT COUNT(*) FROM n a, n b, n c ...
general log:            KILL QUERY 40001
proxy log:              handshake: real thread id 29 -> client sees 40001

With 1.7.1 the same query stops at 5 s with maximum statement execution time exceeded, because of #465. The kill path itself is unchanged.

In production we saw this behind Teleport: one missed kill per timed-out query, a few hundred per week, with one query left running for 14 days.

Proxy used for the repro:

idproxy.py
import asyncio, itertools, struct

UP_HOST, UP_PORT = "mysql", 3306
fake_ids = itertools.count(40001)

def rewrite_handshake(pkt):
    body = bytearray(pkt[4:])
    end = body.index(0, 1)                      # protocol(1) + NUL-terminated server version
    struct.pack_into("<I", body, end + 1, next(fake_ids))
    return pkt[:4] + bytes(body)

async def pipe(r, w):
    try:
        while data := await r.read(65536):
            w.write(data); await w.drain()
    finally:
        w.close()

async def handle(cr, cw):
    ur, uw = await asyncio.open_connection(UP_HOST, UP_PORT)
    hdr = await ur.readexactly(4)
    pkt = hdr + await ur.readexactly(hdr[0] | hdr[1] << 8 | hdr[2] << 16)
    cw.write(rewrite_handshake(pkt)); await cw.drain()
    await asyncio.gather(pipe(cr, uw), pipe(ur, cw), return_exceptions=True)

async def main():
    async with await asyncio.start_server(handle, "0.0.0.0", 3306) as srv:
        await srv.serve_forever()

asyncio.run(main())

Suggested fix

Read the real id from the server once per new pool connection, in the same hook that already runs SET SESSION max_execution_time (#465), and use it for the kill:

SELECT CONNECTION_ID()

CONNECTION_ID() is evaluated by the backend, so it is correct behind any proxy. Falling back to conn.threadId only if that query fails keeps today's behaviour for direct connections. MariaDB has the same function.

Happy to send a PR if the approach works for you.

Lingua principale
TypeScript
Stelle
4k
Fork
370
Merge medio
6h 28m
PR unite (30g)
41

Preparare l'ambiente

  • Include un Dockerfile o un file Docker Compose
  • Nessun modello di pull request
  • Nessuna guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di bytebase/dbhub

Tutte le issue di bytebase/dbhub

Issue simili

Altre issue su TypeScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.