Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1ZtjmX-000634-OE for pgsql-bugs@arkaria.postgresql.org; Tue, 03 Nov 2015 22:10:21 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.84) (envelope-from ) id 1ZtjmX-00075n-A0 for pgsql-bugs@arkaria.postgresql.org; Tue, 03 Nov 2015 22:10:21 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84) (envelope-from ) id 1ZtjmW-00075g-Gq for pgsql-bugs@postgresql.org; Tue, 03 Nov 2015 22:10:20 +0000 Received: from d.mail.sonic.net ([64.142.111.50]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84) (envelope-from ) id 1ZtjmS-00008E-1h for pgsql-bugs@postgresql.org; Tue, 03 Nov 2015 22:10:20 +0000 Received: from engels (162-236-13-58.lightspeed.sntcca.sbcglobal.net [162.236.13.58]) (authenticated bits=0) by d.mail.sonic.net (8.15.1/8.15.1) with ESMTPSA id tA3MA5rd012431 (version=TLSv1.2 cipher=DHE-RSA-AES128-SHA256 bits=128 verify=NOT); Tue, 3 Nov 2015 14:10:05 -0800 Date: Tue, 3 Nov 2015 14:10:06 -0800 From: David Gould To: Jeff Janes Cc: Tom Lane , Alvaro Herrera , Pg Bugs Subject: Re: BUG #13750: Autovacuum slows down with large numbers of tables. More workers makes it slower. Message-ID: <20151103141006.5a87bba2@engels> In-Reply-To: <20151030231952.70eb5887@engels> References: <20151030133252.3033.4249@wrigleys.postgresql.org> <20151030134646.GE5726@alvherre.pgsql> <20151030072704.1a4db344@engels> <20151030151711.GF5726@alvherre.pgsql> <13594.1446219627@sss.pgh.pa.us> <20151030231952.70eb5887@engels> X-Mailer: Claws Mail 3.11.1 (GTK+ 2.24.23; x86_64-pc-linux-gnu) MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="MP_/OHRroPim9CGO95HxESh5ypZ" X-Sonic-CAuth: UmFuZG9tSVafPi49vj54C8caXjua8Cx3jedq/LvdChHLgner3qjT/EAqh0d3bLFMOw8zSqF/AhOkzAdV8ct7HRnxTIHjrvMJ X-Sonic-ID: C;GokPo3eC5RGWH+K7sH9FTg== M;CGZOo3eC5RGWH+K7sH9FTg== X-Spam-Flag: No X-Sonic-Spam-Details: 0.0/5.0 by cerberusd X-Pg-Spam-Score: -2.6 (--) List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-bugs Precedence: bulk Sender: pgsql-bugs-owner@postgresql.org --MP_/OHRroPim9CGO95HxESh5ypZ Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit Content-Disposition: inline On Fri, 30 Oct 2015 23:19:52 -0700 David Gould wrote: > The attached patch against REL9_5_STABLE_goes a little further. It > claims the table under the lock, but also addresses the problem of all the > workers racing to redo the same table by enforcing an ordering on all the > workers. No worker can claim a table with an oid smaller than the highest > oid claimed by any worker. That is, instead of racing to the same table, > workers leapfrog over each other. > > In theory the recheck of the stats could be eliminated although this patch > does not do that. It does eliminate the special handling of stats snapshots > for autovacuum workers which cuts back on the excess rewriting of the stats > file somewhat. > > I'll send numbers shortly, but as I recall it is over 100 times better than > the original. I sent performance test data and a setup for reproducing it elsewhere in the thread. I also ran tests on a larger system (128GB mem, many cores, 2x SSD with battery backed raid). This is for an idle system with 100,000 new small tables to analyze. I ran all the test for an hour or 5000 tables processed. "jj" refers to the patch from Jeff Janes, "dg" refers to the attached patch (same as previous). /autovacuum actions per minute/ workers 9.5b1 jj dg ------- ----- ---- ----- 1 183 171 285 4 45 212 1158 8 23 462 1225 Could someone please take a look at the patch and comment? Thanks. -dg -- David Gould 510 282 0869 daveg@sonic.net If simplicity worked, the world would be overrun with insects. --MP_/OHRroPim9CGO95HxESh5ypZ Content-Type: text/x-patch Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename=autovacuum_worker_contention.diff diff -rcpb a/backend/postmaster/autovacuum.c b/backend/postmaster/autovacuum.c *** a/backend/postmaster/autovacuum.c 2015-10-05 12:09:44.000000000 -0700 --- b/backend/postmaster/autovacuum.c 2015-10-26 05:52:16.857928285 -0700 *************** db_comparator(const void *a, const void *** 1063,1068 **** --- 1063,1083 ---- return (((const avl_dbase *) a)->adl_score < ((const avl_dbase *) b)->adl_score) ? 1 : -1; } + + /* qsort comparison function for oids */ + static int + oid_cmp(const void *p1, const void *p2) + { + Oid v1 = *((const Oid *) p1); + Oid v2 = *((const Oid *) p2); + + if (v1 < v2) + return -1; + if (v1 > v2) + return 1; + return 0; + } + /* * do_start_worker * *************** do_autovacuum(void) *** 1884,1899 **** HeapTuple tuple; HeapScanDesc relScan; Form_pg_database dbForm; - List *table_oids = NIL; HASHCTL ctl; HTAB *table_toast_map; - ListCell *volatile cell; PgStat_StatDBEntry *shared; PgStat_StatDBEntry *dbentry; BufferAccessStrategy bstrategy; ScanKeyData key; TupleDesc pg_class_desc; int effective_multixact_freeze_max_age; /* * StartTransactionCommand and CommitTransactionCommand will automatically --- 1899,1916 ---- HeapTuple tuple; HeapScanDesc relScan; Form_pg_database dbForm; HASHCTL ctl; HTAB *table_toast_map; PgStat_StatDBEntry *shared; PgStat_StatDBEntry *dbentry; BufferAccessStrategy bstrategy; ScanKeyData key; TupleDesc pg_class_desc; int effective_multixact_freeze_max_age; + Oid *table_oids; + int maxoids, + numoids, + oid_idx; /* * StartTransactionCommand and CommitTransactionCommand will automatically *************** do_autovacuum(void) *** 1978,1983 **** --- 1995,2005 ---- &ctl, HASH_ELEM | HASH_BLOBS); + /* create an array of all the tables that might need action */ + maxoids = 32; + table_oids = (Oid *) palloc(maxoids * sizeof(Oid)); + numoids = 0; + /* * Scan pg_class to determine which tables to vacuum. * *************** do_autovacuum(void) *** 2071,2077 **** { /* relations that need work are added to table_oids */ if (dovacuum || doanalyze) ! table_oids = lappend_oid(table_oids, relid); /* * Remember the association for the second pass. Note: we must do --- 2093,2107 ---- { /* relations that need work are added to table_oids */ if (dovacuum || doanalyze) ! { ! if (numoids >= maxoids) ! { ! maxoids *= 2; ! table_oids = (Oid *) repalloc(table_oids, ! maxoids * sizeof(Oid)); ! } ! table_oids[numoids++] = relid; ! } /* * Remember the association for the second pass. Note: we must do *************** do_autovacuum(void) *** 2155,2167 **** /* ignore analyze for toast tables */ if (dovacuum) ! table_oids = lappend_oid(table_oids, relid); } heap_endscan(relScan); heap_close(classRel, AccessShareLock); /* * Create a buffer access strategy object for VACUUM to use. We want to * use the same one across all the vacuum operations we perform, since the * point is for VACUUM not to blow out the shared cache. --- 2185,2214 ---- /* ignore analyze for toast tables */ if (dovacuum) ! { ! if (numoids >= maxoids) ! { ! maxoids *= 2; ! table_oids = (Oid *) repalloc(table_oids, ! maxoids * sizeof(Oid)); ! } ! table_oids[numoids++] = relid; ! } ! } heap_endscan(relScan); heap_close(classRel, AccessShareLock); /* + * Sort the oids to establish a consistent order between multiple workers + * so that by maintaining a high watermark of the most recently examined + * oid workers can avoid competing to vacuum the same table. + */ + if (numoids > 1) + qsort(table_oids, numoids, sizeof(Oid), oid_cmp); + + /* * Create a buffer access strategy object for VACUUM to use. We want to * use the same one across all the vacuum operations we perform, since the * point is for VACUUM not to blow out the shared cache. *************** do_autovacuum(void) *** 2181,2191 **** /* * Perform operations on collected tables. */ ! foreach(cell, table_oids) { - Oid relid = lfirst_oid(cell); autovac_table *tab; ! bool skipit; int stdVacuumCostDelay; int stdVacuumCostLimit; dlist_iter iter; --- 2228,2238 ---- /* * Perform operations on collected tables. */ ! for(oid_idx = 0; oid_idx < numoids; ) { autovac_table *tab; ! Oid relid; ! Oid highwateroid; int stdVacuumCostDelay; int stdVacuumCostLimit; dlist_iter iter; *************** do_autovacuum(void) *** 2209,2277 **** } /* ! * hold schedule lock from here until we're sure that this table still ! * needs vacuuming. We also need the AutovacuumLock to walk the ! * worker array, but we'll let go of that one quickly. */ ! LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE); ! LWLockAcquire(AutovacuumLock, LW_SHARED); ! /* ! * Check whether the table is being vacuumed concurrently by another ! * worker. */ ! skipit = false; dlist_foreach(iter, &AutoVacuumShmem->av_runningWorkers) { WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur); ! /* ignore myself */ ! if (worker == MyWorkerInfo) ! continue; ! /* ignore workers in other databases */ ! if (worker->wi_dboid != MyDatabaseId) ! continue; - if (worker->wi_tableoid == relid) - { - skipit = true; - break; - } - } LWLockRelease(AutovacuumLock); ! if (skipit) ! { ! LWLockRelease(AutovacuumScheduleLock); continue; - } /* * Check whether pgstat data still says we need to vacuum this table. ! * It could have changed if something else processed the table while ! * we weren't looking. ! * ! * Note: we have a special case in pgstat code to ensure that the ! * stats we read are as up-to-date as possible, to avoid the problem ! * that somebody just finished vacuuming this table. The window to ! * the race condition is not closed but it is very small. */ MemoryContextSwitchTo(AutovacMemCxt); tab = table_recheck_autovac(relid, table_toast_map, pg_class_desc, effective_multixact_freeze_max_age); if (tab == NULL) - { /* someone else vacuumed the table, or it went away */ - LWLockRelease(AutovacuumScheduleLock); continue; - } - - /* - * Ok, good to go. Store the table in shared memory before releasing - * the lock so that other workers don't vacuum it concurrently. - */ - MyWorkerInfo->wi_tableoid = relid; - LWLockRelease(AutovacuumScheduleLock); /* * Remember the prevailing values of the vacuum cost GUCs. We have to --- 2256,2313 ---- } /* ! * Scan the sorted array of table oids looking for the first one that has ! * not already been claimed for consideration by some autovacuum. ! * We hold the Autovacuum lock to walk the worker array and to update ! * our WorkerInfo with the chosen candidate table. */ ! LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE); /* ! * Find the highest oid for any table claimed by another worker. */ ! highwateroid = relid = InvalidOid; dlist_foreach(iter, &AutoVacuumShmem->av_runningWorkers) { WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur); ! if (worker->wi_dboid == MyDatabaseId ! && worker->wi_tableoid >= highwateroid) ! highwateroid = worker->wi_tableoid; ! } ! /* ! * Skip past the highwater oid to find the next table to to consider ! * vacuuming. There may not be one, but either way, store our choice ! * in shared memory before releasing the lock so that other workers ! * can see it. This avoids workers racing to vacuum the same table. ! */ ! while (oid_idx < numoids && relid <= highwateroid) ! relid = table_oids[oid_idx++]; ! if (relid <= highwateroid) ! relid = InvalidOid; ! MyWorkerInfo->wi_tableoid = relid; LWLockRelease(AutovacuumLock); ! ! /* Is there a table to work on? */ ! if (relid == InvalidOid) continue; /* * Check whether pgstat data still says we need to vacuum this table. ! * It could have changed if something else processed the table or even ! * dropped it while we weren't looking. ! * FIXME: This re-check is not really needed since workers won't try to ! * vacuum the same table. It could protect against a manual vacuum if ! * that was started after we built the table list and before now, but it ! * is a lot of overhead to protect against a low probability scenario. */ MemoryContextSwitchTo(AutovacMemCxt); tab = table_recheck_autovac(relid, table_toast_map, pg_class_desc, effective_multixact_freeze_max_age); if (tab == NULL) /* someone else vacuumed the table, or it went away */ continue; /* * Remember the prevailing values of the vacuum cost GUCs. We have to *************** table_recheck_autovac(Oid relid, HTAB *t *** 2479,2487 **** bool wraparound; AutoVacOpts *avopts; ! /* use fresh stats */ ! autovac_refresh_stats(); ! shared = pgstat_fetch_stat_dbentry(InvalidOid); dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId); --- 2515,2529 ---- bool wraparound; AutoVacOpts *avopts; ! /* ! * FIXME: For the immediate fix just comment out the call to ! * autovac_refresh_stats() as it drives the stats collector wild. ! * We don't need it because workers no longer compete for tables ! * to vacuum. Longer term, most of this re-checking duplicates work ! * done to build the original list of tables to vacuum. All that is ! * needed here is to make sure the table was not dropped and to ! * retrieve the table details. ! */ shared = pgstat_fetch_stat_dbentry(InvalidOid); dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId); *************** AutoVacuumShmemInit(void) *** 2961,2986 **** * such refreshing in the autovacuum launcher. This is mostly to avoid * rereading the pgstats files too many times in quick succession when there * are many databases. - * - * Note: we avoid throttling in the autovac worker, as it would be - * counterproductive in the recheck logic. */ static void autovac_refresh_stats(void) { - if (IsAutoVacuumLauncherProcess()) - { static TimestampTz last_read = 0; TimestampTz current_time; current_time = GetCurrentTimestamp(); - if (!TimestampDifferenceExceeds(last_read, current_time, STATS_READ_DELAY)) return; last_read = current_time; - } - pgstat_clear_snapshot(); } --- 3003,3020 ---- diff -rcpb a/backend/postmaster/pgstat.c b/backend/postmaster/pgstat.c *** a/backend/postmaster/pgstat.c 2015-10-05 12:09:44.000000000 -0700 --- b/backend/postmaster/pgstat.c 2015-10-22 06:12:43.356049410 -0700 *************** backend_read_statsfile(void) *** 4545,4554 **** /* * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL * msec before now. This indirectly ensures that the collector ! * needn't write the file more often than PGSTAT_STAT_INTERVAL. In ! * an autovacuum worker, however, we want a lower delay to avoid ! * using stale data, so we use PGSTAT_RETRY_DELAY (since the ! * number of workers is low, this shouldn't be a problem). * * We don't recompute min_ts after sleeping, except in the * unlikely case that cur_ts went backwards. So we might end up --- 4545,4551 ---- /* * We set the minimum acceptable timestamp to PGSTAT_STAT_INTERVAL * msec before now. This indirectly ensures that the collector ! * needn't write the file more often than PGSTAT_STAT_INTERVAL. * * We don't recompute min_ts after sleeping, except in the * unlikely case that cur_ts went backwards. So we might end up *************** backend_read_statsfile(void) *** 4559,4570 **** * actually accept. */ ref_ts = cur_ts; ! if (IsAutoVacuumWorkerProcess()) ! min_ts = TimestampTzPlusMilliseconds(ref_ts, ! -PGSTAT_RETRY_DELAY); ! else ! min_ts = TimestampTzPlusMilliseconds(ref_ts, ! -PGSTAT_STAT_INTERVAL); } /* --- 4556,4562 ---- * actually accept. */ ref_ts = cur_ts; ! min_ts = TimestampTzPlusMilliseconds(ref_ts, -PGSTAT_STAT_INTERVAL); } /* diff -rcpb a/include/storage/lwlock.h b/include/storage/lwlock.h *** a/include/storage/lwlock.h 2015-10-05 12:09:44.000000000 -0700 --- b/include/storage/lwlock.h 2015-10-22 03:40:14.715893232 -0700 *************** extern PGDLLIMPORT LWLockPadded *MainLWL *** 117,123 **** #define BtreeVacuumLock (&MainLWLockArray[20].lock) #define AddinShmemInitLock (&MainLWLockArray[21].lock) #define AutovacuumLock (&MainLWLockArray[22].lock) - #define AutovacuumScheduleLock (&MainLWLockArray[23].lock) #define SyncScanLock (&MainLWLockArray[24].lock) #define RelationMappingLock (&MainLWLockArray[25].lock) #define AsyncCtlLock (&MainLWLockArray[26].lock) --- 117,122 ---- --MP_/OHRroPim9CGO95HxESh5ypZ Content-Type: text/plain Content-Disposition: inline Content-Transfer-Encoding: 8bit MIME-Version: 1.0 -- Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-bugs --MP_/OHRroPim9CGO95HxESh5ypZ--