F.2. amcheck
Модуль amcheck предоставляет функции, позволяющие проверять логическую целостность структуры индексов. Если нарушения структуры не обнаруживаются, эти функции отрабатывают без ошибок.
Эти функции проверяют различные инварианты в структуре представления определённых индексов. Правильность работы функций методов доступа, стоящих за сканированием индекса и другими важными операциями, зависит от всегда соблюдаемых инвариантов. Например, определённые функции проверяют, помимо остальных вещей, что все страницы B-дерева содержат элементы в «логическом» порядке (например, индекс-B-дерево, построенный по столбцу text, должен содержать кортежи, упорядоченные в лексическом порядке с учётом правила сортировки). Если этот конкретный инвариант каким-то образом нарушается, следует ожидать, что бинарный поиск на затронутой странице введёт в заблуждение процедуру сканирования индекса, что приведёт к неверным результатам запросов SQL.
Проверка выполняется теми же процедурами, что используются при сканировании индекса, и это может быть код пользовательского класса операторов. Например, проверка индекса-B-дерева задействует сравнения, выполняемые одной или несколькими опорными функциями B-дерева под номером 1. Подробнее опорные функции класса операторов описываются в Подразделе 37.14.3.
Функции amcheck могут выполнять только суперпользователи.
F.2.1. Функции
-
bt_index_check(index regclass) returns void bt_index_checkпроверяет, соблюдаются ли в целевом объекте, индексе-B-дереве, различные инварианты. Пример использования:test=# SELECT bt_index_check(c.oid), c.relname, c.relpages FROM pg_index i JOIN pg_opclass op ON i.indclass[0] = op.oid JOIN pg_am am ON op.opcmethod = am.oid JOIN pg_class c ON i.indexrelid = c.oid JOIN pg_namespace n ON c.relnamespace = n.oid WHERE am.amname = 'btree' AND n.nspname = 'pg_catalog' -- Не проверять временные таблицы (они могут относиться к другим сеансам): AND c.relpersistence != 't' -- Функция может выдать ошибку без этих условий: AND i.indisready AND i.indisvalid ORDER BY c.relpages DESC LIMIT 10; bt_index_check | relname | relpages ----------------+---------------------------------+---------- | pg_depend_reference_index | 43 | pg_depend_depender_index | 40 | pg_proc_proname_args_nsp_index | 31 | pg_description_o_c_o_index | 21 | pg_attribute_relid_attnam_index | 14 | pg_proc_oid_index | 10 | pg_attribute_relid_attnum_index | 9 | pg_amproc_fam_proc_index | 5 | pg_amop_opr_fam_index | 5 | pg_amop_fam_strat_index | 5 (10 rows)Этот пример демонстрирует сеанс проверки 10 самых больших индексов системных каталогов в базе данных «test». Так как ошибки не было, все проверенные индексы представляются логически целостными. Естественно, этот запрос можно легко изменить, чтобы функция
bt_index_checkвызывалась для всех индексов в базе данных, которые поддерживают эту проверку.Функция
bt_index_checkзапрашивает блокировкуAccessShareLockдля целевого индекса и отношения, которому он принадлежит. Это тот же режим блокировки, что запрашивается для отношений обычными операторамиSELECT.bt_index_checkне проверяет инварианты, существующие в иерархии потомок/родитель, а также не проверяет, соответствует ли целевой индекс основному отношению. Когда в работающей производственной среде требуется регулярная лёгкая проверка на наличие нарушений, использованиеbt_index_checkчасто будет подходящим компромиссом между полнотой проверки и минимизацией влияния на производительность и доступность приложения.-
bt_index_parent_check(index regclass) returns void Функция
bt_index_parent_checkпроверяет, соблюдаются ли в целевом объекте, индексе-B-дереве, различные инварианты. Проверки, выполняемые функциейbt_index_parent_check, включают в себя все проверки, которые выполняетbt_index_check. Функциюbt_index_parent_checkможно считать более полноценным вариантомbt_index_check: в отличие отbt_index_check,bt_index_parent_checkпроверяет и инварианты, существующие в иерархии родитель/потомок. Однако и она не проверяет, соответствует ли целевой индекс основному отношению. Функцияbt_index_parent_checkследует общему соглашению и выдаёт ошибку в случае обнаружения логической несогласованности или другой проблемы.Функция
bt_index_parent_checkзапрашивает в целевом индексе блокировкуShareLock(такжеShareLockзапрашивается и в основном отношении). Эти блокировки предотвращают одновременное изменение данных командамиINSERT,UPDATEиDELETE. Эти блокировки также препятствуют одновременной обработке нижележащего отношения командойVACUUMи другими вспомогательными командами. Заметьте, что эта функция удерживает блокировки только во время выполнения, а не на протяжении всей транзакции.Дополнительные проверки, проводимые функцией
bt_index_parent_check, более ориентированы на выявление различных патологических случаев. В том числе это может быть неправильно реализованный класс операторов B-дерева, используемый проверяемым индексом, или, гипотетически, неизвестные ошибки в нижележащем коде метода доступа индекса-B-дерева. Заметьте, что функциюbt_index_parent_checkнельзя применять, когда включён режим горячего резерва (то есть на физических репликах в режиме «только чтение»), в отличие отbt_index_check.
F.2.2. Эффективное использование amcheck
Модуль amcheck может быть полезен для выявления различных типов проблем, которые могут остаться незамеченными при включении контрольных сумм страниц данных. В частности это:
Структурные несоответствия, возникающие при некорректной реализации класса операторов.
В том числе это проблемы, возникающие при изменении правил сравнения в операционной системе. Сравнения данных сортируемого типа, например
text, должны быть постоянными (как и все сравнения, применяемые при сканировании индекса-B-дерева), что подразумевает неизменность правил сортировки в операционной системе. Проблемы могут возникать при обновлениях правил в операционной системе, хотя такие случаи редки. Чаще проявляются несоответствия порядка сортировки между ведущим и ведомым сервером, например, из-за различий основных версий используемых операционных систем. Возникающие расхождения обычно наблюдаются только на ведомых серверах, так что и выявить их обычно можно только на них.Когда возникает подобная проблема, она может затрагивать не абсолютно все индексы, построенные с порочным правилом сортировки, просто потому что индексированные значения могут иметь тот же абсолютный порядок, независящий от различий поведения. За дополнительными сведениями об использовании в PostgreSQL правил сортировки и локалей операционной системы обратитесь к Разделу 23.1 и Разделу 23.2.
Повреждения, вызванные гипотетическими неизвестными ошибками в нижележащем коде методов доступа PostgreSQL или коде сортировки.
Автоматическая проверка структурной целостности индексов играет важную роль в общем тестировании новых или предлагаемых возможностей PostgreSQL, с которыми может возникнуть логическая несогласованность. И поэтому одна из очевидных стратегий тестирования — регулярно вызывать функции
amcheckпри проведении стандартных регрессионных тестов. Подробнее о выполнении тестов можно узнать в Разделе 32.1.Ошибки в файловой системе или подсистеме хранения, когда просто не включены контрольные суммы.
Заметьте, что
amcheckрассматривает страницу в том виде, как она представлена в некотором буфере разделяемой памяти к моменту проверки, если при обращению к нужному блоку он уже находится в разделяемом буфере. Вследствие этого,amcheckне обязательно видит данные, находящиеся в файловой системе в момент проверки. Заметьте, что когда контрольные суммы включены,amcheckможет выдать ошибку из-за несоответствия контрольных сумм, если в буфер будет считываться испорченный блок.Повреждения, вызванные дефектными чипами ОЗУ или вообще подсистемой памяти.
PostgreSQL не защищает от ошибок памяти; предполагается, что в эксплуатируемом вами сервере установлена память с ECC (Error Correcting Codes, Коды исправления ошибок) или лучшая защита. Однако память ECC обычно защищает только от ошибок в одном бите и не следует считать её абсолютной защитой от сбоев, приводящих к повреждению памяти.
Вообще говоря, amcheck может доказать только наличие повреждений, но не доказать их отсутствие.
F.2.3. Исправление повреждений
Выдаваемые amcheck ошибки, относящиеся к повреждениям данных, никогда не должны быть ложными. На практике amcheck с большей вероятностью обнаружит программные ошибки, чем проблемы с оборудованием. amcheck выдаёт ошибки в случае условий, которые никогда не должны наблюдаться по определению, так что ошибки amcheck, как правило, требует тщательного анализа.
Общего метода устранения проблем, которые может выявить amcheck, не существует. Начать нужно с поиска корня проблемы, приводящей к нарушению инварианта. Полезную роль в диагностике повреждений, которые выявляет amcheck, может сыграть pageinspect. Одна лишь команда REINDEX может быть неэффективна, когда потребуется исправить повреждения.
F.2. amcheck
The amcheck module provides functions that allow you to verify the logical consistency of the structure of indexes. If the structure appears to be valid, no error is raised.
The functions verify various invariants in the structure of the representation of particular indexes. The correctness of the access method functions behind index scans and other important operations relies on these invariants always holding. For example, certain functions verify, among other things, that all B-Tree pages have items in “logical” order (e.g., for B-Tree indexes on text, index tuples should be in collated lexical order). If that particular invariant somehow fails to hold, we can expect binary searches on the affected page to incorrectly guide index scans, resulting in wrong answers to SQL queries.
Verification is performed using the same procedures as those used by index scans themselves, which may be user-defined operator class code. For example, B-Tree index verification relies on comparisons made with one or more B-Tree support function 1 routines. See Section 37.14.3 for details of operator class support functions.
amcheck functions may only be used by superusers.
F.2.1. Functions
-
bt_index_check(index regclass) returns void bt_index_checktests that its target, a B-Tree index, respects a variety of invariants. Example usage:test=# SELECT bt_index_check(c.oid), c.relname, c.relpages FROM pg_index i JOIN pg_opclass op ON i.indclass[0] = op.oid JOIN pg_am am ON op.opcmethod = am.oid JOIN pg_class c ON i.indexrelid = c.oid JOIN pg_namespace n ON c.relnamespace = n.oid WHERE am.amname = 'btree' AND n.nspname = 'pg_catalog' -- Don't check temp tables, which may be from another session: AND c.relpersistence != 't' -- Function may throw an error when this is omitted: AND i.indisready AND i.indisvalid ORDER BY c.relpages DESC LIMIT 10; bt_index_check | relname | relpages ----------------+---------------------------------+---------- | pg_depend_reference_index | 43 | pg_depend_depender_index | 40 | pg_proc_proname_args_nsp_index | 31 | pg_description_o_c_o_index | 21 | pg_attribute_relid_attnam_index | 14 | pg_proc_oid_index | 10 | pg_attribute_relid_attnum_index | 9 | pg_amproc_fam_proc_index | 5 | pg_amop_opr_fam_index | 5 | pg_amop_fam_strat_index | 5 (10 rows)This example shows a session that performs verification of the 10 largest catalog indexes in the database “test”. Since no error is raised, all indexes tested appear to be logically consistent. Naturally, this query could easily be changed to call
bt_index_checkfor every index in the database where verification is supported.bt_index_checkacquires anAccessShareLockon the target index and the heap relation it belongs to. This lock mode is the same lock mode acquired on relations by simpleSELECTstatements.bt_index_checkdoes not verify invariants that span child/parent relationships, nor does it verify that the target index is consistent with its heap relation. When a routine, lightweight test for corruption is required in a live production environment, usingbt_index_checkoften provides the best trade-off between thoroughness of verification and limiting the impact on application performance and availability.-
bt_index_parent_check(index regclass) returns void bt_index_parent_checktests that its target, a B-Tree index, respects a variety of invariants. The checks performed bybt_index_parent_checkare a superset of the checks performed bybt_index_check.bt_index_parent_checkcan be thought of as a more thorough variant ofbt_index_check: unlikebt_index_check,bt_index_parent_checkalso checks invariants that span parent/child relationships. However, it does not verify that the target index is consistent with its heap relation.bt_index_parent_checkfollows the general convention of raising an error if it finds a logical inconsistency or other problem.A
ShareLockis required on the target index bybt_index_parent_check(aShareLockis also acquired on the heap relation). These locks prevent concurrent data modification fromINSERT,UPDATE, andDELETEcommands. The locks also prevent the underlying relation from being concurrently processed byVACUUM, as well as all other utility commands. Note that the function holds locks only while running, not for the entire transaction.bt_index_parent_check's additional verification is more likely to detect various pathological cases. These cases may involve an incorrectly implemented B-Tree operator class used by the index that is checked, or, hypothetically, undiscovered bugs in the underlying B-Tree index access method code. Note thatbt_index_parent_checkcannot be used when Hot Standby mode is enabled (i.e., on read-only physical replicas), unlikebt_index_check.
F.2.2. Using amcheck effectively
amcheck can be effective at detecting various types of failure modes that data page checksums will always fail to catch. These include:
Structural inconsistencies caused by incorrect operator class implementations.
This includes issues caused by the comparison rules of operating system collations changing. Comparisons of datums of a collatable type like
textmust be immutable (just as all comparisons used for B-Tree index scans must be immutable), which implies that operating system collation rules must never change. Though rare, updates to operating system collation rules can cause these issues. More commonly, an inconsistency in the collation order between a master server and a standby server is implicated, possibly because the major operating system version in use is inconsistent. Such inconsistencies will generally only arise on standby servers, and so can generally only be detected on standby servers.If a problem like this arises, it may not affect each individual index that is ordered using an affected collation, simply because indexed values might happen to have the same absolute ordering regardless of the behavioral inconsistency. See Section 23.1 and Section 23.2 for further details about how PostgreSQL uses operating system locales and collations.
Corruption caused by hypothetical undiscovered bugs in the underlying PostgreSQL access method code or sort code.
Automatic verification of the structural integrity of indexes plays a role in the general testing of new or proposed PostgreSQL features that could plausibly allow a logical inconsistency to be introduced. One obvious testing strategy is to call
amcheckfunctions continuously when running the standard regression tests. See Section 32.1 for details on running the tests.File system or storage subsystem faults where checksums happen to simply not be enabled.
Note that
amcheckexamines a page as represented in some shared memory buffer at the time of verification if there is only a shared buffer hit when accessing the block. Consequently,amcheckdoes not necessarily examine data read from the file system at the time of verification. Note that when checksums are enabled,amcheckmay raise an error due to a checksum failure when a corrupt block is read into a buffer.Corruption caused by faulty RAM, or the broader memory subsystem.
PostgreSQL does not protect against correctable memory errors and it is assumed you will operate using RAM that uses industry standard Error Correcting Codes (ECC) or better protection. However, ECC memory is typically only immune to single-bit errors, and should not be assumed to provide absolute protection against failures that result in memory corruption.
In general, amcheck can only prove the presence of corruption; it cannot prove its absence.
F.2.3. Repairing corruption
No error concerning corruption raised by amcheck should ever be a false positive. In practice, amcheck is more likely to find software bugs than problems with hardware. amcheck raises errors in the event of conditions that, by definition, should never happen, and so careful analysis of amcheck errors is often required.
There is no general method of repairing problems that amcheck detects. An explanation for the root cause of an invariant violation should be sought. pageinspect may play a useful role in diagnosing corruption that amcheck detects. A REINDEX may not be effective in repairing corruption.