Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1l1qXt-0002oh-QF for pgsql-bugs@arkaria.postgresql.org; Tue, 19 Jan 2021 12:55:42 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1l1qXq-0005GO-DC for pgsql-bugs@arkaria.postgresql.org; Tue, 19 Jan 2021 12:55:38 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1l1ozW-0002UF-K7 for pgsql-bugs@lists.postgresql.org; Tue, 19 Jan 2021 11:16:06 +0000 Received: from mail-wr1-x434.google.com ([2a00:1450:4864:20::434]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.92) (envelope-from ) id 1l1ozR-0001Dl-Bi for pgsql-bugs@lists.postgresql.org; Tue, 19 Jan 2021 11:16:05 +0000 Received: by mail-wr1-x434.google.com with SMTP id w5so19305821wrm.11 for ; Tue, 19 Jan 2021 03:16:00 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=deepbluecap-com.20150623.gappssmtp.com; s=20150623; h=to:from:subject:message-id:date:user-agent:mime-version :content-language; bh=kXS9CfASHZopFXUloM5UxoWad97cdgnF9Q+wqAIPy+c=; b=SBklROXUBmj20A+opkZbuD5aXauvb20fUAe6mTCoFtALTl93sIZPlb4F3/wwa3yUHV pH5YAKjCPnW5VS++dJEdPm4gwbG8AKUCsBuUaDlKBKhX6VgJ9B2VMwRZe0CMIMkvG2n1 eFiMylnYcsIRMI/AC6w3UKs+t9p64U29sukX9eS5dowVJ5EBf3NCHYIu7o6j3fcvsLEN vcRDj1re1Uq5pClcbSFc6N/fxJkMSP75PX8RkYDrUxnB5ShcZmIrWtyDqtAu3KSQQo9E aBxw5s0/CvBByvJWVpnF8JZHigtZu3wiET9If//FluDXjtPEFuu4tgNMWDvZ66G8yExT Sxcw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:to:from:subject:message-id:date:user-agent :mime-version:content-language; bh=kXS9CfASHZopFXUloM5UxoWad97cdgnF9Q+wqAIPy+c=; b=qlQDtYRe31BsK5vMWJVx3jy/Hl8nxcmQAs+AYVrrI8TjNy3pdQjaGR7cEIHa2u81rm sY8V29fTYUQEsMSjaFpNgG06ZwlHnOcIEJFFSoNQRdTAgSJQpRUAgRWO2GtrFgXPnXYs 5g7sFkr5Xl2APRPUn6ql7dXqBBGa/zAcS1oAuxHGvBYSX07hmy6Rnyb4nokbQ0FBj5nu WYWoCBVdRz5SaT+LUhEqtxnFpwUJV0q6FiHuzYPp6A/FYlIu5ONuvpbaLNYikqBkX6LY INxjDJYjJ1xOQ2qagJ6LJkLDKHJHpTzf8Wl4sWXigIod1w+L3qeaBt9x7LHDHzHw6kMC NSjg== X-Gm-Message-State: AOAM533H0+sHtd8foCcAHfnsFLIe0aTIybxPFxWuq96kwMCWWhJ/emHz FNf8l/wsNqjPX/0uAK3AnvDpK0IEm4psWVrRdsJauGf+Y/OqCKrm8OS/nsAKV4sB55/igEEcL3R jDm2QFuDg5g1ZiFNClwsZTLan9P7yhnItymP/OZwALSUcaSOPwfdxvoJT2Mqvk6yrdm9gK8T/fa 2sqlIPApl8yLTSD/WPog== X-Google-Smtp-Source: ABdhPJxGC/2sdwnvxmFyqd+Kvqv3doDYhwKw/D02Li7murm6Luj6Eko39qI7pUMS4VRgF5ZTxOci7A== X-Received: by 2002:adf:dc10:: with SMTP id t16mr3908856wri.345.1611054958949; Tue, 19 Jan 2021 03:15:58 -0800 (PST) Received: from ?IPv6:2a01:e0a:255:1000:259d:a6ad:1416:4635? ([2a01:e0a:255:1000:259d:a6ad:1416:4635]) by smtp.gmail.com with ESMTPSA id u17sm3832987wmj.35.2021.01.19.03.15.58 for (version=TLS1_3 cipher=TLS_AES_128_GCM_SHA256 bits=128/128); Tue, 19 Jan 2021 03:15:58 -0800 (PST) To: pgsql-bugs@lists.postgresql.org From: Duncan Sands Subject: Reproducible GIST index corruption under concurrent updates Message-ID: Date: Tue, 19 Jan 2021 12:15:57 +0100 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Thunderbird/78.5.0 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------9BAC13B6F8B38425C29A13F0" Content-Language: en-US List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk This is a multi-part message in MIME format. --------------9BAC13B6F8B38425C29A13F0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit To reproduce, run the attached python3 script after adjusting CONNECTION_STRING appropriately. The target database should have the btree_gist extension installed. If it fails due to making too many connections to the database, try reducing NUM_THREADS (or allowing more connections). Example bad output (may take a minute or two): $ ./gist_issue.py inconsistent: 9286 Each "inconsistent" line means that looking up by "id" in the "sections" table returns a row but looking up by "file" doesn't, even though "id" and "file" are always the same: duncan=> SELECT * FROM sections WHERE id=9286; id | file | valid ------+------+--------------- 9286 | 9286 | (,1970-01-01) (1 row) duncan=> SELECT * FROM sections WHERE file=9286; id | file | valid ----+------+------- (0 rows) What is going on here is that querying by "file" uses the GIST index but this index is corrupt: duncan=> EXPLAIN SELECT * FROM sections WHERE file=9286; QUERY PLAN ------------------------------------------------------------------------------------------ Index Scan using sections_file_valid_excl on sections (cost=0.15..2.37 rows=1 width=18) Index Cond: (file = 9286) (2 rows) If the "gist_issue.py" script runs forever then it failed to reproduce the problem. Reproduces with postgres 13.1 on Linux (ubuntu groovy, package 13.1-1.pgdg20.10+1, x86-64). I reproduced it with default database settings and with a tuned database, and on multiple Linux machines. Enjoy! Best wishes, Duncan. --------------9BAC13B6F8B38425C29A13F0 Content-Type: text/x-python; charset=UTF-8; name="gist_issue.py" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="gist_issue.py" #!/usr/bin/env python3 # Shows a corruption in gist indexes, when multiple threads are involved. CONNECTION_STRING="dbname=duncan" # CHANGE THIS TO SUIT YOU. # You will also need to do: CREATE EXTENSION btree_gist; import datetime import psycopg2.extras import threading NUM_THREADS = 32 META_IDS_PER_THREAD = 100 CHECK_EVERY = 100 with psycopg2.connect(CONNECTION_STRING) as conn: with conn.cursor() as cursor: cursor.execute( """ DROP TABLE IF EXISTS files CASCADE; CREATE TABLE files ( id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, meta INTEGER NOT NULL ); DROP TABLE IF EXISTS sections CASCADE; CREATE TABLE sections ( id INTEGER PRIMARY KEY, file INTEGER NOT NULL REFERENCES files, valid DATERANGE NOT NULL, EXCLUDE USING gist(file WITH =, valid WITH &&) ); """ ) found_problem = False class Worker(threading.Thread): def __init__(self, lower, upper): # upper not included super().__init__() self.lower = lower self.upper = upper def run(self): global found_problem try: check_counter = 0 metaid = self.lower with psycopg2.connect(CONNECTION_STRING) as conn: with conn.cursor() as cursor: while not found_problem: metaid = metaid + 1 if metaid >= self.upper: metaid = self.lower cursor.execute( "SELECT sections.id, valid FROM sections" " JOIN files ON sections.file = files.id WHERE meta=%s" " ORDER BY files.id DESC LIMIT 1", (metaid, )) r = cursor.fetchone() if not r: cursor.execute("BEGIN") cursor.execute( "INSERT INTO files(meta) VALUES (%s) RETURNING id", (metaid, ) ) fileid = cursor.fetchone() cursor.execute( "INSERT INTO sections(id,file,valid) VALUES (" " %s, %s, '(,)')", (fileid, fileid, ) ) cursor.execute("COMMIT") cursor.execute( "SELECT sections.id, valid FROM sections" " JOIN files ON sections.file = files.id WHERE meta=%s" " ORDER BY files.id DESC LIMIT 1", (metaid, )) r = cursor.fetchone() if not r: found_problem = True return row, valid = r cursor.execute("BEGIN") if valid.lower: mid = valid.lower + datetime.timedelta(days=1) else: mid = datetime.date(1970, 1, 1) v1 = psycopg2.extras.DateRange( valid.lower, mid, '[)', empty=valid.lower and valid.lower >= mid) v2 = psycopg2.extras.DateRange( mid, valid.upper, '[)', empty=valid.upper and mid >= valid.upper) add_1 = not v1.isempty add_2 = not v2.isempty # split ranges if add_1 or add_2: cursor.execute( "DELETE FROM sections WHERE id=%s", (row, )) if add_1: cursor.execute( "INSERT INTO files(meta) VALUES (%s) RETURNING id", (metaid, ) ) file1 = cursor.fetchone() cursor.execute( "INSERT INTO sections(id,file,valid) VALUES (" " %s, %s, %s::daterange)", (file1, file1, v1)) if add_2: cursor.execute( "INSERT INTO files(meta) VALUES (%s) RETURNING id", (metaid, ) ) file2 = cursor.fetchone() cursor.execute( "INSERT INTO sections(id,file,valid) VALUES (" " %s, %s, %s::daterange)", (file2, file2, v2)) cursor.execute("COMMIT") check_counter = check_counter + 1 if check_counter % CHECK_EVERY == 0: cursor.execute( "SELECT id FROM files WHERE meta>=%s AND meta<%s", (self.lower, self.upper)) ids = [row[0] for row in cursor] for i in ids: cursor.execute("SELECT * FROM sections WHERE id=%s", (i, )) has1 = cursor.fetchone() is not None cursor.execute("SELECT * FROM sections WHERE file=%s", (i, )) has2 = cursor.fetchone() is not None if has1 != has2: found_problem = True return except: found_problem = True raise workers = [Worker(j*META_IDS_PER_THREAD, (j+1)*META_IDS_PER_THREAD) for j in range(0, NUM_THREADS)] for w in workers: w.start() for w in workers: w.join() with psycopg2.connect(CONNECTION_STRING) as conn: with conn.cursor() as cursor: cursor.execute("SELECT id FROM files") ids = [row[0] for row in cursor] for i in ids: cursor.execute("SELECT * FROM sections WHERE id=%s", (i, )) has1 = cursor.fetchone() is not None cursor.execute("SELECT * FROM sections WHERE file=%s", (i, )) has2 = cursor.fetchone() is not None if has1 != has2: print("inconsistent: %s" %i) --------------9BAC13B6F8B38425C29A13F0--