Не подтверждена Коммит 08af69f4 создал по автору Юрьев ЛЕОНИД ВАЛЕРЬЕВИЧ's avatar Юрьев ЛЕОНИД ВАЛЕРЬЕВИЧ 💬
Просмотр файлов

mdbx: next cycle of bug-bounty trip.

Please see the ChangeLog.md for a more structured enumeration of the changes.

2026-10-28 mdbx++: missing `#include <optional>`.
2026-10-28 mdbx: reformat/cosmetics.
2026-10-28 feat(mcp-memory): multiplatform scanning — win32 cross-scan, orchestrator, fail-loudly (#227)
2026-10-28 mdbx: update ChangeLog.
2026-10-28 mdbx: fix memory leak in case a table name with zero length.
2026-10-28 ci: orchestrate ci-dispatch runs (dedup + cancel superseded/rewritten)
2026-10-28 docs: runbook for codebase-memory-mcp diagnostics and recovery
2026-10-28 windows: fuses against using POSIX error codes.
2026-10-27 fix: clear the shrink throttle after a successful shrink (issue #217)
2026-10-27 build: probe __builtin_cpu_supports() availability for Clang on x86/x64
2026-10-27 test: cover lckless weak-checkpoint reopen (issue #215)
2026-10-27 mdbx: fix comment on lckless meta latch; add test-only fault site for lckless open
2026-10-27 docs: describe the CI v3.5 change-addressed gate model
2026-10-27 test-ci: replace hand-maintained path_zones with self-verifying change-addressed gate
2026-10-27 mdbx: update ChangeLog.
2026-10-27 tests: abbreviation of prefixes in names.
2026-10-27 fix(mcp-memory): run_coverage missed padded ctest numbers and regex metachars
2026-10-27 mdbx: add MDBX_DBG_ERR for mdbx_setup_debug().
2026-10-26 ChangeLog: note MDBX_EXCLUSIVE no longer slows down durable commits on Windows (#179)
2026-10-26 tests: add `--prepare-only` option to stochastic script.
2026-10-26 tests/docs: let gh0170_throttle reuse the shared test PCH; note the examples-PCH
2026-10-26 fix: keep the normal durable i/o path for MDBX_EXCLUSIVE on Windows (#179)
2026-10-26 build: precompile the common C++ example headers and share them
2026-10-26 test: add regression for MDBX_EXCLUSIVE durable i/o path on Windows (#179)
2026-10-26 tests: cover the shrink-attempt throttling and its option (issue #170)
2026-10-27 build: consolidate the precompiled-header setup into a shared helper
2026-10-26 ChangeLog: note surfacing of ignored auxiliary page-write errors (#203)
2026-10-26 mdbx: skip doomed datafile-shrink attempts and rate-limit them (issue #170)
2026-10-25 tests: cover deferred-shrink logical<physical scenarios (issue #173)
2026-10-26 fix: stop silently ignoring auxiliary page-write errors (#203)
2026-10-26 cmake/tests: fix tests flaky timeouts on CI.
2026-10-26 mcp-tests: fix retry loop in the SIGKILL weak-checkpoint test
2026-10-26 test: surface ignored auxiliary page-write errors (#203)
2026-10-26 ci: stop passing ccache to the VS-generator cells; bump cache size (#204)
2026-10-26 build: add `make test-doxygen` strict audit of the doxygen comments
2026-10-26 ci: dynamic build parallelism, phase metrics, longest-first ordering, PCH gate (#201)
2026-10-26 docs: complete the doxygen comments of the C and C++ public API
2026-10-25 ci: rebalance Windows cell matrix and extend PR preflight (#192)
2026-10-25 mdbx: LIBMDBX_INLINE_API for mdbx_preopen_snapinfo().
2026-10-25 mcp-memory: preopen now reports MDBX_WANNA_RECOVERY on a weak checkpoint
2026-10-25 examples: make the C++ example build on Windows with C++ < 17
2026-10-25 tests: cover preopen weak-checkpoint handling across all four modes
2026-10-25 mdbx: add mdbx_preopen_snapinfo_ex() with explicit weak-checkpoint modes
2026-10-26 mdbx: add `MDBX_PATHNAME_T()` macro like the `_T` on Windows.
2026-10-25 mdbx: update ChangeLog.
2026-10-25 ChangeLog: note removal of the MDBX_ENABLE_REFUND build option
2026-10-25 mdbx: remove the MDBX_ENABLE_REFUND build option
2026-10-25 mdbx: fix osal_fseek_shut() leaving a failing offset in *safe_parking_lot_offset
2026-10-25 docs: document GTEST_RUNTIME_DEADLINE and the test-build optimisations
2026-10-24 tests: cover an idle-open database losing its semaphore set to a colliding open (issue #159)
2026-10-25 tests: precompile the shared gtest header once and reuse it everywhere
2026-10-23 mcp-memory: close all bot notes, physical-lock tests, docs sync (F5 #4)
2026-10-25 sysv: redesign and rewrite ftok collision detection.
2026-10-25 tests: compile the shared test-env TU once as an object library
2026-10-24 ChangeLog: note the nested DUPSORT sub-page offset/upper validation fix (#176)
2026-10-23 mcp-memory: child catches mcp.errors.MemoryError, not stdlib (F5 #B2)
2026-10-24 mdbx: more IS_WINDOWS macro.
2026-10-25 tests: runtime_limiter on steady_clock with an absolute UTC deadline
2026-10-24 tests: build the suite at the requested C++ standard; gate newer-standard tests
2026-10-24 fix: validate nested DUPSORT sub-page offsets/geometry on all paths (#176)
2026-10-23 mcp-memory: claim/reserve — GB copy outside the state lock (F5 #B3)
2026-10-24 mdbx: add nasan/pelican/stir mixers.
2026-10-24 test: add regression for nested DUPSORT sub-page offset/upper validation (#176)
2026-10-23 mcp-memory: revert R1 — next_auto = last_auto + interval always (F5 #B1)
2026-10-22 mcp-memory: CodeQL cleanup + T2 writers + cross-path lock + bot with-style + SKILL (F5 #4)
2026-10-22 mcp-memory: de-flake race tests — busy_io catch, waitpid rc, polling barrier (F5 #R3-R5)
2026-10-22 mcp-memory: lock-degradation flag per-path, not per-process (F5 #R2)
2026-10-22 mcp-memory: next_auto correct during backoff — don't lie to the monitor (F5 #R1)
2026-10-22 mcp-memory: lock-degradation in backup_notice + backoff field + SKILL honesty (F5 round 3 #8, D1-D4)
2026-10-22 mcp-memory: race/invariant tests — purge-vs-activate, state-merge races, SCHEMA all families (F5 round 3)
2026-10-22 mcp-memory: limit flag visible during the backoff window (F5.1 #5)
2026-10-22 mcp-memory: AUTO state block under one lock + pre-limit resets backoff (F5.1 #6, #6a)
2026-10-22 mcp-memory: SKILL.md — schema contracts, purge CAS, backoff, search-flush honesty (F5 round 2 docs)
2026-10-22 mcp-memory: CLI with-Store style (bot) + concurrency/schema-boundary tests (F5 round 2)
2026-10-22 mcp-memory: exponential backoff for non-limit auto failures + loud lock degrade (F5.1 #2,#4)
2026-10-22 mcp-memory: SCHEMA_OUTDATED everywhere for optional-table methods (F5.2 #7)
2026-10-22 mcp-memory: make branch_purge CAS atomic inside the write txn (F5.4a #12)
2026-10-22 mcp-memory: CLI ops + backup_status contract + auto-resume test (F5.4c/M7-14)
2026-10-22 mcp-memory: document LRU touch semantics for the swarm (F5.4b/M4-6+M12)
2026-10-22 mcp-memory: swarm concurrency hardening — purge CAS, honest warning, pin realpath (F5.4a)
2026-10-22 mcp-memory: jitter in busy-retry backoff — break swarm phase lock (F5.3/R4)
2026-10-22 mcp-memory: schema-version mismatch → explicit contract errors (F5.2/R2)
2026-10-22 mcp-memory: swarm-safe backup state — merge + lock + timer-on-success (F5.1/R1)
2026-10-24 cmake: fix `warning: ‘MDBX_CHECKING’ redefined`.
2026-10-24 docs: fold English-only pages into the RU search index
2026-10-23 sysv & posix: fix/rework ftok-collision detection and lck_destroy() internals.
2026-10-22 mdbx: rework unsync/nometasync degradation in deferred-shrink cases.
2026-10-20 tests: cover pnl stale and duplicated-page rejection in GC
2026-10-23 mprobes: rename and cleanup.
2026-10-21 docs(changelog): Windows remap_lock deadlock fix (issue #154)
2026-10-22 doc: more cross-references in doxygen comments.
2026-10-22 fix: compacting copy wakes the producer when the writer thread fails
2026-10-22 mdbx: reject a page listed by two GC records during reclamation
2026-10-23 mprobes: fixed silent crashes when `MDBX_PROBES` is not enabled via env.
2026-10-21 windows: fix remap_lock deadlock between a long-lived reader and file growth
2026-10-23 mdbx: inner split LCK-file initialization to upper/bottom halves.
2026-10-21 refactor: rename txn_shrink_allowed to txn_unmap_allowed
2026-10-21 mcp-memory: ops-hygiene docs + guards (D5/N13-N16)
2026-10-22 fix(cxx): cursor reserve methods use blank_for_put_reserve, as txn ones do
2026-10-23 mdbx: rework osal_ftok() internals.
2026-10-21 mcp-memory: expose writer-contention metrics in db_status (D4/N12)
2026-10-21 fix(cxx): buffer transcode-appends copy a source that reaches the own tailroom
2026-10-23 mdbx: always log sysv-ftok collision check errors.
2026-10-21 mcp-memory: fork-safe Env guard + periodic reader-slot cleanup (D3/N11)
2026-10-21 fix: cursor_get_batch(MDBX_FIRST) always rewinds to the first pair
2026-10-23 tests: add `--dlc` (don't compress logs) option to `tests/stochastic`.
2026-10-21 mcp-memory: split db_backup (pin) / db_export; backup limit + TOCTOU flag (D2/N10)
2026-10-21 tests: unify the proprietary license header in every test file
2026-10-23 mdbx: fix size_t casting/trucation and MSVC warnings.
2026-10-21 mcp-memory: recall/search no longer inflate LRU stats by default (D1/N9)
2026-10-21 tests: add the runtime-limiter guard to every gtest TEST/TEST_P
2026-10-21 mcp-memory: document layer lifecycle APIs (purge/migrate/C2 tools)
2026-10-22 tests-framework: treat `--duration` and `--nops` as two independent limiters for compatibility with previous scripts.
2026-10-22 fix: mdbx_replace() with MDBX_RESERVE skips the dirty-page shortcut and rejects dup maps
2026-10-21 mcp-memory: coverage_migrate — carry a branch's coverage into merge target (C3/N5)
2026-10-21 mcp-memory: expose map_put_symbol/map_alias/map_refresh_stale via MCP (C2/N6)
2026-10-21 fix: txn_clone rejects ousted parked origin and foreign/origin handles
2026-10-21 docs: Wine is not a valid substitute for Windows CI in testing/debugging
2026-10-21 mcp-memory: branch_purge — drop a layer with all its data (C1/N5)
2026-10-21 mcp-memory: fix same-prefix branch diff + honest summary comment (B2 review)
2026-10-20 mcp-memory: purge without a full links scan (A4/N7,N8)
2026-10-21 mcp-memory: bound memory of map_diff_branches/trace_path/summary (B2/N4)
2026-10-20 c++: reject null pointer with non-zero length across slice/buffer; try_as_pod; docs (issues #142-146)
2026-10-20 mcp-memory: batched coverage/metrics writes for CI pipelines (A3/N2)
2026-10-21 mcp-memory: consistent single-transaction reads for dashboards (B1/N3)
2026-10-20 mcp-memory: data producers for the coverage/porting goals (commit B)
2026-10-20 mcp-memory: chunked map_load_batch to release the writer lock (A2/N2)
2026-10-21 mcp-memory: address F1 review notes (chunk-load window + links_in orphan)
2026-10-20 tests: runtime limiter + CI-only CRT popup suppression
2026-10-20 mcp-memory: shared-graph-memory toolbox for deep refactoring & test coverage
2026-10-20 mcp-memory: per-process layer isolation for the agent swarm (A1/N1)
2026-10-20 c++: keep buffer(0, N)/assign(0, N) a compile error (issue #137)
2026-10-20 sysv-locking: refuse a colliding open of a live database (issue #80)
2026-10-19 fix: get_batch for any limit, C++ doc warnings, stronger regressions
2026-10-19 sysv-locking: add MDBX_AVOID_FTOK and factor the EEXIST decision (issue #80)
2026-10-19 fix: nested-rollback restart failure and txn_clone bailout crashes
2026-10-19 fix: buffer append/add_header bytes for content+tailroom sources
2026-10-19 docs: fix search worker URLs after the asset hoist
2026-10-18 mcp-memory: address critical review — BM25 search, structural layer, test/coverage collectors, auto-vocab
2026-10-19 docs/doc_audit: address code-quality review — close files, drop dead globals
2026-10-19 docs: promote the Change Log to the root contents of both locales
2026-10-19 docs: freeze the doxygen redirect table, drop the superseded audit scripts
2026-10-19 tools: add `MDBX_MAYBE_UNUSED` for common.h
2026-10-19 docs: build the API reference from the headers only, drop the text-page pipeline
2026-10-19 docs: turn header page-references into living site links
2026-10-19 docs: absorb the doxygen text fragments into the locale trees
2026-10-19 docs: add a Quick CRUD cheat-sheet and document APPEND semantics
владелец b5dea3a0
# libmdbx — agent guide # libmdbx — agent guide
_Package: v0.15.0-139-g634a8449 (2026-10-19T08:59:22+03:00)_ _Package: v0.15.0-333-gebaaa06d (2026-10-28T23:41:11+03:00)_
_libmdbx_ is an embedded transactional key-value database: compact, extremely fast _libmdbx_ is an embedded transactional key-value database: compact, extremely fast
(memory-mapped, B+tree, O(log N)), ACID, crash-safe by default, no WAL, no server (memory-mapped, B+tree, O(log N)), ACID, crash-safe by default, no WAL, no server
......
...@@ -616,6 +616,8 @@ add_option(MDBX MMAP_NEEDS_JOLT "Assume system needs explicit syscall to sync/fl ...@@ -616,6 +616,8 @@ add_option(MDBX MMAP_NEEDS_JOLT "Assume system needs explicit syscall to sync/fl
mark_as_advanced(MDBX_MMAP_NEEDS_JOLT) mark_as_advanced(MDBX_MMAP_NEEDS_JOLT)
add_option(MDBX LOCKING "Locking method (Windows=-1, SystemV=5, POSIX=1988, POSIX=2001, POSIX=2008)" AUTO) add_option(MDBX LOCKING "Locking method (Windows=-1, SystemV=5, POSIX=1988, POSIX=2001, POSIX=2008)" AUTO)
mark_as_advanced(MDBX_LOCKING) mark_as_advanced(MDBX_LOCKING)
add_option(MDBX AVOID_FTOK "Use own collision-resistant key derivation for System V IPC instead of the system ftok()" OFF)
mark_as_advanced(MDBX_AVOID_FTOK)
add_option(MDBX TRUST_RTC "Does a system have battery-backed Real-Time Clock or just a fake" AUTO) add_option(MDBX TRUST_RTC "Does a system have battery-backed Real-Time Clock or just a fake" AUTO)
mark_as_advanced(MDBX_TRUST_RTC) mark_as_advanced(MDBX_TRUST_RTC)
add_option( add_option(
...@@ -624,7 +626,16 @@ add_option( ...@@ -624,7 +626,16 @@ add_option(
"Disable some checks to reduce an overhead and detection probability of database corruption to a values closer to the LMDB" "Disable some checks to reduce an overhead and detection probability of database corruption to a values closer to the LMDB"
OFF) OFF)
mark_as_advanced(MDBX_DISABLE_VALIDATION) mark_as_advanced(MDBX_DISABLE_VALIDATION)
add_option(MDBX ENABLE_REFUND "Zerocost auto-compactification during write-transactions" ON) if(WIN32)
set(MDBX_ENABLE_EXCLUSIVE_FASTPATH_DEFAULT ON)
else()
set(MDBX_ENABLE_EXCLUSIVE_FASTPATH_DEFAULT OFF)
endif()
add_option(
MDBX ENABLE_EXCLUSIVE_FASTPATH
"On Windows keep the normal write-through/dsync i/o path in MDBX_EXCLUSIVE mode, enforcing exclusivity by constant byte-range locks instead of an unshareable data file"
${MDBX_ENABLE_EXCLUSIVE_FASTPATH_DEFAULT})
mark_as_advanced(MDBX_ENABLE_EXCLUSIVE_FASTPATH)
add_option(MDBX ENABLE_BIGFOOT add_option(MDBX ENABLE_BIGFOOT
"Chunking long list of retired pages during huge transactions commit to avoid use sequences of pages" ON) "Chunking long list of retired pages during huge transactions commit to avoid use sequences of pages" ON)
add_option(MDBX ENABLE_PGOP_STAT "Gathering statistics on pages modification operations" ON) add_option(MDBX ENABLE_PGOP_STAT "Gathering statistics on pages modification operations" ON)
...@@ -891,6 +902,15 @@ target_include_directories( ...@@ -891,6 +902,15 @@ target_include_directories(
if(MDBX_CLANG_BUILTINS_LIB) if(MDBX_CLANG_BUILTINS_LIB)
target_link_libraries(mdbx-static INTERFACE "${MDBX_CLANG_BUILTINS_LIB}") target_link_libraries(mdbx-static INTERFACE "${MDBX_CLANG_BUILTINS_LIB}")
endif() endif()
if(MDBX_CLANG_CPU_RT_LIB)
# Normalized in cmake/compiler.cmake (backslash Windows paths are invalid here).
if(NOT MDBX_CLANG_CPU_RT_LINK)
file(TO_CMAKE_PATH "${MDBX_CLANG_CPU_RT_LIB}" MDBX_CLANG_CPU_RT_LINK)
endif()
if(MDBX_CLANG_CPU_RT_LINK AND NOT MDBX_CLANG_CPU_BUILTINS_OK)
target_link_libraries(mdbx-static INTERFACE "${MDBX_CLANG_CPU_RT_LINK}")
endif()
endif()
# ###################################################################################################################### # ######################################################################################################################
...@@ -945,6 +965,14 @@ if(MDBX_BUILD_SHARED_LIBRARY) ...@@ -945,6 +965,14 @@ if(MDBX_BUILD_SHARED_LIBRARY)
if(MDBX_CLANG_BUILTINS_LIB) if(MDBX_CLANG_BUILTINS_LIB)
target_link_libraries(mdbx PRIVATE "${MDBX_CLANG_BUILTINS_LIB}") target_link_libraries(mdbx PRIVATE "${MDBX_CLANG_BUILTINS_LIB}")
endif() endif()
if(MDBX_CLANG_CPU_RT_LIB)
if(NOT MDBX_CLANG_CPU_RT_LINK)
file(TO_CMAKE_PATH "${MDBX_CLANG_CPU_RT_LIB}" MDBX_CLANG_CPU_RT_LINK)
endif()
if(MDBX_CLANG_CPU_RT_LINK AND NOT MDBX_CLANG_CPU_BUILTINS_OK)
target_link_libraries(mdbx PRIVATE "${MDBX_CLANG_CPU_RT_LINK}")
endif()
endif()
endif() endif()
if(MDBX_BUILD_SHARED_LIBRARY AND MDBX_LINK_TOOLS_NONSTATIC) if(MDBX_BUILD_SHARED_LIBRARY AND MDBX_LINK_TOOLS_NONSTATIC)
......
Это отличие свёрнуто
...@@ -5,7 +5,7 @@ clean install install-no-strip install-strip strip tools uninstall \ ...@@ -5,7 +5,7 @@ clean install install-no-strip install-strip strip tools uninstall \
bench bench-clean bench-couple bench-quartet bench-triplet re-bench \ bench bench-clean bench-couple bench-quartet bench-triplet re-bench \
lib libs lib-static lib-shared tools-static \ lib libs lib-static lib-shared tools-static \
libmdbx mdbx mdbx_chk mdbx_copy mdbx_drop mdbx_dump mdbx_load mdbx_stat mdbx_defrag \ libmdbx mdbx mdbx_chk mdbx_copy mdbx_drop mdbx_dump mdbx_load mdbx_stat mdbx_defrag \
check dist memcheck cross-gcc cross-qemu gcc-analyzer reformat docsite books \ check dist memcheck cross-gcc cross-qemu gcc-analyzer reformat docsite test-doxygen books \
release-assets tags build-test mdbx_test \ release-assets tags build-test mdbx_test \
smoke smoke-fault smoke-singleprocess smoke-assertion smoke-memcheck \ smoke smoke-fault smoke-singleprocess smoke-assertion smoke-memcheck \
test test-assertion test-long test-long-assertion test-ci test-ci-extra \ test test-assertion test-long test-long-assertion test-ci test-ci-extra \
......
{ "git_describe": "v0.15.0-139-g634a8449", "git_timestamp": "2026-10-19T08:59:22+03:00", "git_tree": "ae85592ba9ff0e806adb96781f672330eedf5a0d", "git_commit": "634a844915a39e0123d5e79513e6eec797d34050", "semver": "0.15.0.139" } { "git_describe": "v0.15.0-333-gebaaa06d", "git_timestamp": "2026-10-28T23:41:11+03:00", "git_tree": "a916c217d153c5590cd0292a6f5330c84fdbbe3c", "git_commit": "ebaaa06d91fc4a1b7b36824e07a298e36996a911", "semver": "0.15.0.333" }
...@@ -455,6 +455,54 @@ if(CMAKE_C_COMPILER_LOADED) ...@@ -455,6 +455,54 @@ if(CMAKE_C_COMPILER_LOADED)
endif() endif()
endif() endif()
# Probing __builtin_cpu_supports() on Clang for x86/x64: it pulls in
# __cpu_model/__cpu_indicator_init from compiler-rt, which is not always
# linked automatically (and may be absent on the target). The MSVC-LLVM clang
# is the key non-Linux case: it needs the clang_rt builtins library, whose
# Windows path is a backslash string that must be normalized before it is
# put into CMAKE_REQUIRED_LIBRARIES. Only for Clang the result line is emitted
# into config-cmake.h as MDBX_HAVE_BUILTIN_CPU_SUPPORTS (0/1). For any other
# compiler, or when MDBX_HAVE_BUILTIN_CPU_SUPPORTS was already provided on the
# command line, the engine decides by itself (options.h).
unset(MDBX_X86_CPU_FEATURES_DEFINE)
if(CMAKE_COMPILER_IS_CLANG AND (X86_32 OR X86_64) AND NOT DEFINED MDBX_HAVE_BUILTIN_CPU_SUPPORTS)
set(_probe_src "int main(void){__builtin_cpu_init(); return __builtin_cpu_supports(\"sse2\")?0:1;}")
set(_save_libs ${CMAKE_REQUIRED_LIBRARIES})
set(_save_flags ${CMAKE_REQUIRED_FLAGS})
set(CMAKE_REQUIRED_FLAGS "-O0")
check_c_source_compiles("${_probe_src}" MDBX_CLANG_CPU_BUILTINS_OK)
if(MDBX_CLANG_CPU_BUILTINS_OK)
message(STATUS "Clang x86: __builtin_cpu_supports() links directly")
set(MDBX_X86_CPU_FEATURES_DEFINE "#define MDBX_HAVE_BUILTIN_CPU_SUPPORTS 1")
else()
execute_process(
COMMAND "${CMAKE_C_COMPILER}" --rtlib=compiler-rt -print-libgcc-file-name
OUTPUT_VARIABLE MDBX_CLANG_CPU_RT_LIB
OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_VARIABLE _rt_err
RESULT_VARIABLE _rt_rc)
if(_rt_rc EQUAL 0 AND EXISTS "${MDBX_CLANG_CPU_RT_LIB}")
# Normalize any backslash Windows path (e.g. MSVC-LLVM clang_rt builtins)
# so it parses in CMake code without '\' escapes.
file(TO_CMAKE_PATH "${MDBX_CLANG_CPU_RT_LIB}" MDBX_CLANG_CPU_RT_LIB_CMAKE)
set(CMAKE_REQUIRED_LIBRARIES "${MDBX_CLANG_CPU_RT_LIB_CMAKE}")
check_c_source_compiles("${_probe_src}" MDBX_CLANG_CPU_BUILTINS_RT_OK)
if(MDBX_CLANG_CPU_BUILTINS_RT_OK)
message(STATUS "Clang x86: __builtin_cpu_supports() via ${MDBX_CLANG_CPU_RT_LIB}")
set(MDBX_X86_CPU_FEATURES_DEFINE "#define MDBX_HAVE_BUILTIN_CPU_SUPPORTS 1")
else()
message(STATUS "Clang x86: __builtin_cpu_supports() unusable even with compiler-rt")
set(MDBX_X86_CPU_FEATURES_DEFINE "#define MDBX_HAVE_BUILTIN_CPU_SUPPORTS 0")
endif()
else()
message(STATUS "Clang x86: __builtin_cpu_supports() needs compiler-rt, but it is absent")
set(MDBX_X86_CPU_FEATURES_DEFINE "#define MDBX_HAVE_BUILTIN_CPU_SUPPORTS 0")
endif()
endif()
set(CMAKE_REQUIRED_LIBRARIES ${_save_libs})
set(CMAKE_REQUIRED_FLAGS ${_save_flags})
endif()
# Check for LTO support by GCC # Check for LTO support by GCC
if(CMAKE_COMPILER_IS_GNU${CMAKE_PRIMARY_LANG} if(CMAKE_COMPILER_IS_GNU${CMAKE_PRIMARY_LANG}
AND NOT CMAKE_COMPILER_IS_ELBRUSC AND NOT CMAKE_COMPILER_IS_ELBRUSC
......
# Copyright (c) 2015-2026 Леонид Юрьев aka Leonid Yuriev <leo@yuriev.ru> ###############################################
# SPDX-License-Identifier: Apache-2.0
#
# Shared precompiled-header infrastructure.
#
# Precompiling the headers every translation unit needs anyway (GoogleTest, the
# libmdbx APIs, the common standard headers) saves minutes on a clean build:
# each gtest binary and each C++ example is a single TU, so without a PCH the
# same headers are re-parsed once per binary. A single anchor library owns the
# PCH and every consumer reuses it via target_precompile_headers(REUSE_FROM ...).
#
# target_precompile_headers()/REUSE_FROM need CMake >= 3.16 while the project
# itself still builds on 3.12, so the PCH is an opt-in acceleration gated on
# the CMake version rather than a raised project-wide minimum. The gate is
# expressed by which definition of the <name>_apply macro is in effect (the
# real one is defined here alongside the anchor, a no-op fallback after this
# file), so call sites never carry a version branch.
#
# REUSE_FROM requires the compile flags of the anchor and of every reusing
# target to match: the same C++ standard, the same include dirs and the same
# PIC/PIE mode. The anchor mirrors the consumers' flags (passed as arguments),
# and a consumer whose flags differ (e.g. an MDBX_PROBES one) simply does not
# reuse the PCH — GCC then falls back to a normal compile without an error, so
# this is safe.
# mdbx_add_pch_anchor(<name> <header> <anchor_source>
# [CXX_STANDARD <n>]
# [INCLUDE <dir>...]
# [LINK <lib>...]
# [LINK_PRIVATE <lib>...])
#
# Creates a static anchor library <name> that precompiles <header>, and defines
# the <name>_apply(<target>) macro that makes a target reuse that PCH. When the
# PCH is disabled (MDBX_ENABLE_PCH=OFF), CMake < 3.16, or the C++ compiler is
# not loaded, the macro is a no-op and no anchor library is created.
#
# The standard, include dirs and (PRIVATE) link libraries are applied to the
# anchor so the precompiled header is produced with the same flags the
# consumers compile with. The anchor is linked PRIVATE so the dependency does
# not propagate to consumers (they link the library themselves).
#
# This is a macro (not a function) on purpose: it must create the anchor
# library and the <name>_apply macro in the *calling* scope, so both become
# visible to the targets declared after the call.
macro(mdbx_add_pch_anchor name header anchor_source)
cmake_parse_arguments(PCH "" "CXX_STANDARD" "INCLUDE;LINK;LINK_PRIVATE" ${ARGN})
if(MDBX_ENABLE_PCH AND NOT CMAKE_VERSION VERSION_LESS 3.16 AND CMAKE_CXX_COMPILER_LOADED)
add_library(${name} STATIC "${anchor_source}")
if(PCH_INCLUDE)
target_include_directories(${name} PUBLIC ${PCH_INCLUDE})
endif()
if(PCH_LINK)
target_link_libraries(${name} PUBLIC ${PCH_LINK})
endif()
if(PCH_LINK_PRIVATE)
# The anchor is only a PCH carrier, its consumers already link the
# library themselves, so the PRIVATE dependency must not propagate.
target_link_libraries(${name} PRIVATE ${PCH_LINK_PRIVATE})
endif()
# The consumers are executables: with CMAKE_POSITION_INDEPENDENT_CODE on
# Linux/GCC they are compiled -fPIE, while a static library defaults to
# -fPIC. GCC/Clang refuse to reuse a PCH created with different PIC/PIE
# settings (a fatal -Winvalid-pch under -Werror), so build the anchor's
# PCH with the very PIE option the consumers get. Use
# CMAKE_CXX_COMPILE_OPTIONS_PIE rather than a hardcoded -fPIE: it is
# "-fPIE" on Linux/GCC but empty on Windows (MinGW leaves
# COMPILE_OPTIONS_PIE empty and MSVC has no such flag), which is exactly
# where the executables are built without -fPIE.
set_target_properties(${name} PROPERTIES POSITION_INDEPENDENT_CODE OFF)
if(CMAKE_CXX_COMPILE_OPTIONS_PIE AND CMAKE_POSITION_INDEPENDENT_CODE)
target_compile_options(${name} PRIVATE ${CMAKE_CXX_COMPILE_OPTIONS_PIE})
endif()
if(PCH_CXX_STANDARD)
set_target_properties(${name} PROPERTIES CXX_STANDARD ${PCH_CXX_STANDARD} CXX_STANDARD_REQUIRED ON)
endif()
target_precompile_headers(${name} PRIVATE "${header}")
# Real definition of the apply helper, in effect only when the anchor was
# built; call sites just invoke <name>_apply() with no branch.
macro(${name}_apply target)
target_link_libraries(${target} ${name})
target_precompile_headers(${target} REUSE_FROM ${name})
endmacro()
else()
macro(${name}_apply target)
endmacro()
endif()
endmacro()
/* This file is part of the libmdbx amalgamated source code (v0.15.0-139-g634a8449 at 2026-10-19T08:59:22+03:00), /* This file is part of the libmdbx amalgamated source code (v0.15.0-333-gebaaa06d at 2026-10-28T23:41:11+03:00),
* it is the template for libmdbx's config.h * it is the template for libmdbx's config.h
******************************************************************************/ ******************************************************************************/
...@@ -36,13 +36,19 @@ ...@@ -36,13 +36,19 @@
#ifndef MDBX_LOCKING_AUTO #ifndef MDBX_LOCKING_AUTO
#cmakedefine MDBX_LOCKING @MDBX_LOCKING@ #cmakedefine MDBX_LOCKING @MDBX_LOCKING@
#endif #endif
#cmakedefine01 MDBX_AVOID_FTOK
#cmakedefine MDBX_TRUST_RTC_AUTO #cmakedefine MDBX_TRUST_RTC_AUTO
#ifndef MDBX_TRUST_RTC_AUTO #ifndef MDBX_TRUST_RTC_AUTO
#cmakedefine01 MDBX_TRUST_RTC #cmakedefine01 MDBX_TRUST_RTC
#endif #endif
#cmakedefine01 MDBX_DISABLE_VALIDATION #cmakedefine01 MDBX_DISABLE_VALIDATION
#cmakedefine01 MDBX_AVOID_MSYNC #cmakedefine01 MDBX_AVOID_MSYNC
#cmakedefine01 MDBX_ENABLE_REFUND /* Clang on x86/x64: __builtin_cpu_supports() pulls __cpu_model from
* compiler-rt, whose availability is probed at configure time by
* cmake/compiler.cmake. Left empty for other compilers: the engine
* decides by itself (see options.h). */
@MDBX_X86_CPU_FEATURES_DEFINE@
#cmakedefine01 MDBX_ENABLE_EXCLUSIVE_FASTPATH
#cmakedefine01 MDBX_ENABLE_BIGFOOT #cmakedefine01 MDBX_ENABLE_BIGFOOT
#cmakedefine01 MDBX_ENABLE_PGOP_STAT #cmakedefine01 MDBX_ENABLE_PGOP_STAT
#cmakedefine01 MDBX_ENABLE_PGET_STAT #cmakedefine01 MDBX_ENABLE_PGET_STAT
......
...@@ -184,7 +184,7 @@ The most significant ones are listed below. ...@@ -184,7 +184,7 @@ The most significant ones are listed below.
- **GC diagnostics:** `mdbx_gc_info()` (state, histograms, record iteration) and the `gcrtime` - **GC diagnostics:** `mdbx_gc_info()` (state, histograms, record iteration) and the `gcrtime`
counter — time spent searching and reclaiming. counter — time spent searching and reclaiming.
- **Refund/loose pages:** returning freed pages within the current transaction without touching GC - **Refund/loose pages:** returning freed pages within the current transaction without touching GC
(options `MDBX_ENABLE_REFUND`, `MDBX_opt_loose_limit`, `dp_reserve_limit`). (options `MDBX_opt_loose_limit`, `dp_reserve_limit`).
- **RKL** — tracking GC-record identifiers (intervals + lists) with "weighted-reserve" allocation: - **RKL** — tracking GC-record identifiers (intervals + lists) with "weighted-reserve" allocation:
one-pass GC update with O(1)..O(log N) complexity. one-pass GC update with O(1)..O(log N) complexity.
- **Sparse and lock-free DBI handle sets** (`MDBX_ENABLE_DBI_SPARSE`, `MDBX_ENABLE_DBI_LOCKFREE`) — - **Sparse and lock-free DBI handle sets** (`MDBX_ENABLE_DBI_SPARSE`, `MDBX_ENABLE_DBI_LOCKFREE`) —
......
# Quick CRUD reference
> Related: [First steps](first-steps.md) ·
> [Installation and building](install-build.md) ·
> [Textbook: Volume I "Fundamentals"](../textbook/01-tom-i-osnovy.md) ·
> [C API reference](../reference/api/group__c__api.md)
This is a compact cheat-sheet for the most common operations. The authoritative
Quick Reference with the full decision tables is generated from the `mdbx.h`
annotations and lives in the C API reference:
- [Quick Reference for Insert/Update/Delete operations](../reference/api/group__c__crud.md) —
cases for tables with UNIQUE keys and with NON-UNIQUE (DUPSORT) keys, plus the
corresponding flags (`MDBX_NOOVERWRITE`, `MDBX_UPSERT`, `MDBX_CURRENT`,
`MDBX_APPEND`, `MDBX_APPENDDUP`, ...).
## C++ API at a glance
The C++ binding maps the C operations onto `mdbx::txn` and `mdbx::cursor`
methods. The most common ones:
| Operation | `mdbx::txn` | `mdbx::cursor` | C equivalent |
|-----------|-------------|----------------|--------------|
| Insert or fail | `insert(map, key, value)` | `insert(key, value)` | `mdbx_put(MDBX_NOOVERWRITE)` |
| Insert or replace | `upsert(map, key, value)` | `upsert(key, value)` | `mdbx_put(MDBX_UPSERT)` |
| Update existing | `update(map, key, value)` | `update(key, value)` | `mdbx_put(MDBX_CURRENT)` |
| Read | `get(map, key)` | `to_first()/to_find()/...` | `mdbx_get()` |
| Read & remove | `extract(map, key)` | — | `mdbx_replace()` |
| Delete by key | `erase(map, key)` | `erase(key)` | `mdbx_del()` |
| Delete pair | `erase(map, key, value)` | `erase(key, value)` | `mdbx_del()` |
| Append (tail) | `put(map, key, value, MDBX_APPEND)` | `put(key, value, MDBX_APPEND)` | `mdbx_put(MDBX_APPEND)` |
> See the full reference in the [C++ API](../reference/api/classmdbx_1_1txn.md)
> and [cursor](../reference/api/classmdbx_1_1cursor.md) pages.
## Examples
- [`examples/c++/03-crud.c++`](https://sourcecraft.dev/dqdkfa/libmdbx/blob?file=examples/c%2B%2B/03-crud.c%2B%2B) ·
[C version](https://sourcecraft.dev/dqdkfa/libmdbx/blob?file=examples/c/03-crud.c)
- Textbook: [Chapter 4. Basic CRUD operations](../textbook/01-tom-i-osnovy.md)
## Further reading
- [First steps](first-steps.md) — the minimal env → txn → dbi → get/put flow.
- [Durability modes](durability-modes.md) — trade-offs between durability and speed.
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
> Related: [Installation and building](install-build.md) · > Related: [Installation and building](install-build.md) ·
> [Tooling](../reference/tooling.md) · [Restrictions](../overview/restrictions.md) · > [Tooling](../reference/tooling.md) · [Restrictions](../overview/restrictions.md) ·
> [Textbook: Volume I "Fundamentals"](../textbook/01-tom-i-osnovy.md) · > [Textbook: Volume I "Fundamentals"](../textbook/01-tom-i-osnovy.md) ·
> [C API reference](../reference/api/group__c__api.md) > [Quick CRUD](crud-quick.md) · [C API reference](../reference/api/group__c__api.md)
Everything starts with an **environment** (`MDBX_env`): `mdbx_env_create()` → Everything starts with an **environment** (`MDBX_env`): `mdbx_env_create()` →
`mdbx_env_open()` → work → `mdbx_env_close()`. A non-zero `mode` argument of `mdbx_env_open()` → work → `mdbx_env_close()`. A non-zero `mode` argument of
...@@ -89,7 +89,8 @@ one is committed or aborted. Reads are unaffected. ...@@ -89,7 +89,8 @@ one is committed or aborted. Reads are unaffected.
- **Do not use the environment in a child after `fork()`** — libmdbx checks - **Do not use the environment in a child after `fork()`** — libmdbx checks
this at critical points. If needed — this at critical points. If needed —
`mdbx_env_resurrect_after_fork()`. `mdbx_env_resurrect_after_fork()`.
- **No more than one transaction per thread.** Violations are reported with - **No more than one transaction per thread.** A transaction is tied to the
thread by default (Thread Local Storage). Violations are reported with
`MDBX_TXN_OVERLAPPING`, `MDBX_BAD_RSLOT`, `MDBX_BUSY` — unless the `MDBX_TXN_OVERLAPPING`, `MDBX_BAD_RSLOT`, `MDBX_BUSY` — unless the
`MDBX_NOSTICKYTHREADS` option is set (transaction hand-off between threads; `MDBX_NOSTICKYTHREADS` option is set (transaction hand-off between threads;
with it you must know exactly what you are doing). A write transaction must with it you must know exactly what you are doing). A write transaction must
...@@ -125,6 +126,15 @@ while at least one transaction is using it. ...@@ -125,6 +126,15 @@ while at least one transaction is using it.
- Range query result estimation: `mdbx_estimate_*`. - Range query result estimation: `mdbx_estimate_*`.
- Resolving a "database full" caused by slow readers: `mdbx_env_set_hsr()`. - Resolving a "database full" caused by slow readers: `mdbx_env_set_hsr()`.
- Sequences and canary markers: `mdbx_dbi_sequence()`, `MDBX_canary`. - Sequences and canary markers: `mdbx_dbi_sequence()`, `MDBX_canary`.
- Exclusive mode: `MDBX_EXCLUSIVE`.
- Drop and clean a database: `mdbx_drop()`.
- Detect and report errors: the
[`c_err` group](https://libmdbx.dqdkfa.ru/docs/en/reference/api/group__c__err.html).
- Gather statistics about the database: the
[`c_statinfo` group](https://libmdbx.dqdkfa.ru/docs/en/reference/api/group__c__statinfo.html).
- Reduce (temporarily) robustness for more speed: the
[durability modes](durability-modes.md).
- Define custom sort orders (but this is recommended to be avoided).
- [Durability modes](durability-modes.md) — the reliability/performance - [Durability modes](durability-modes.md) — the reliability/performance
trade-offs. trade-offs.
- [Textbook: Volume I](../textbook/01-tom-i-osnovy.md) — the systematic - [Textbook: Volume I](../textbook/01-tom-i-osnovy.md) — the systematic
......
...@@ -6,6 +6,8 @@ and no server process — safe for concurrent multi-process access. ...@@ -6,6 +6,8 @@ and no server process — safe for concurrent multi-process access.
Choose a section: Choose a section:
- **[Change Log](reference/changelog.md)** — the news and latest updates
(kept in English for the international audience).
- **[Overview](overview/index.md)** — what libmdbx is, its characteristics, - **[Overview](overview/index.md)** — what libmdbx is, its characteristics,
comparison with alternatives, and when to choose it (plus the honest list of comparison with alternatives, and when to choose it (plus the honest list of
[restrictions and gotchas](overview/restrictions.md)). [restrictions and gotchas](overview/restrictions.md)).
...@@ -16,8 +18,7 @@ Choose a section: ...@@ -16,8 +18,7 @@ Choose a section:
from the first steps to expert topics and bindings. from the first steps to expert topics and bindings.
- **[Deep dive](deep-dive/architecture.md)** — the architecture, internal - **[Deep dive](deep-dive/architecture.md)** — the architecture, internal
mechanisms, and what libmdbx improves over LMDB. mechanisms, and what libmdbx improves over LMDB.
- **[Reference](reference/index.md)** — the C/C++ API reference, command-line tools, - **[Reference](reference/index.md)** — the C/C++ API reference and command-line tools.
and the change log.
The documentation is available in English and Russian — use the language pill The documentation is available in English and Russian — use the language pill
in the top-right corner of any page to switch. in the top-right corner of any page to switch.
...@@ -49,6 +49,22 @@ set of [improvements](../deep-dive/improvements.md). ...@@ -49,6 +49,22 @@ set of [improvements](../deep-dive/improvements.md).
## Key features ## Key features
- B+tree-based database management library, modeled loosely on the BerkeleyDB
API, but much simplified: the entire database ("environment") is exposed in a
memory map, and all data fetches return data directly from the mapped memory
— **no `malloc`'s or `memcpy`'s occur during data fetches**. The library is
extremely simple (no page-caching layer of its own), extremely high
performance and memory-efficient.
- Fully thread-aware: supports concurrent read/write access from multiple
processes and threads; **writes are fully serialized** — only one write
transaction may be active at a time, which guarantees that writers can never
deadlock.
- The memory map is **read-only by default**, providing total immunity to
corruption from stray pointer writes; read-write mapping offers much higher
write performance, but adds the possibility for stray application writes
through pointers to silently corrupt the database.
- The database structure is multi-versioned, so readers run with no locks;
writers cannot block readers, and readers do not block writers.
- Key-value data model, keys are always sorted; range lookups including range - Key-value data model, keys are always sorted; range lookups including range
query volume estimation. query volume estimation.
- Fully [ACID](https://en.wikipedia.org/wiki/ACID) through - Fully [ACID](https://en.wikipedia.org/wiki/ACID) through
...@@ -136,3 +152,22 @@ Go ([mdbx-go](https://github.com/torquem-ch/mdbx-go)), ...@@ -136,3 +152,22 @@ Go ([mdbx-go](https://github.com/torquem-ch/mdbx-go)),
Python ([PyPi/libmdbx](https://pypi.org/project/libmdbx/)), Python ([PyPi/libmdbx](https://pypi.org/project/libmdbx/)),
.NET ([libmdbx-dotnet](https://public.git.amsoft.spb.ru/libmdbx/libmdbx-dotnet)), .NET ([libmdbx-dotnet](https://public.git.amsoft.spb.ru/libmdbx/libmdbx-dotnet)),
NodeJS ([mdbxmou](https://github.com/ikonopistsev/mdbxmou)) and others. NodeJS ([mdbxmou](https://github.com/ikonopistsev/mdbxmou)) and others.
## Roadmap and the future
- **MithrilDB** — the next-generation engine that removes the architectural
limitations inherited from LMDB: a common API for several storage formats,
reworked long-value handling, fundamental GC/freelist improvements, and no
more trouble with long-lived readers. See the [Textbook: Chapter 33 «Roadmap
and the future: MithrilDB»](../textbook/05-tom-v-ekspertnye-temy.md) and the
[Roadmap](../overview/restrictions.md#roadmap) section.
- **Roadmap presentation** — the annotated slide-deck
«[_libmdbx_: successes, obstacles, goals and roadmap](https://libmdbx.dqdkfa.ru/release/libmdbx-roadmap-HNY2026-english.pdf)»
with important explanations embedded as comments (a
[Russian version](https://libmdbx.dqdkfa.ru/release/libmdbx-roadmap-HNY2026-russian.pdf)).
- **TODO** — the current open directions are tracked in
[`TODO.md`](https://sourcecraft.dev/dqdkfa/libmdbx/browse/TODO.md): new APIs,
WASM, bindings, tracing, and more.
- **SkyNET** (Mission «Concordia Intellectuum») — an experimental AI model, a
coordinated hierarchical swarm/harness, used in the development and
maintenance of _libmdbx_.
...@@ -10,7 +10,20 @@ limitations, operational risks and their mitigations. ...@@ -10,7 +10,20 @@ limitations, operational risks and their mitigations.
## MVCC and "long-lived" readers ## MVCC and "long-lived" readers
The most important operational nuance of libmdbx. The mechanics: every write Understanding the problem of long-lived readers requires a little background,
but it can be difficult for a quick perception. So it is reasonable to
simplify it as follows: the **garbage collection problem exists in all
databases** one way or another — e.g. `VACUUM` in PostgreSQL. But in libmdbx
it is even more discernible because of the high transaction rate and the
intentional simplification of internals in favor of performance: libmdbx
employs [Multiversion concurrency control](https://en.wikipedia.org/wiki/Multiversion_concurrency_control)
on the [copy-on-write](https://en.wikipedia.org/wiki/Copy-on-write) basis,
which allows multiple readers to run in parallel with a write transaction
without blocking. Each write transaction needs free pages for the changed
data; libmdbx efficiently recycles such pages from earlier unused snapshots,
**but this is impossible while a read transaction holds an old snapshot**.
The mechanics: every write
transaction builds a new version of the changed pages (MVCC on a copy-on-write transaction builds a new version of the changed pages (MVCC on a copy-on-write
basis); readers work with snapshots and are never blocked. Pages freed by newer basis); readers work with snapshots and are never blocked. Pages freed by newer
write transactions cannot be reused while at least one active older snapshot write transactions cannot be reused while at least one active older snapshot
......
...@@ -14,8 +14,12 @@ Entry points: ...@@ -14,8 +14,12 @@ Entry points:
and macros, and the C++ API (`mdbx.h++`) and macros, and the C++ API (`mdbx.h++`)
- [Class members](api/class_members.md) · [Macros](api/macros.md) - [Class members](api/class_members.md) · [Macros](api/macros.md)
Also in this section: [command-line tools](tooling.md); The headers themselves, with the complete inline documentation:
[change log](changelog.md).
- [The `mdbx.h` C API header](api/mdbx_8h.md)
- [The `mdbx.h++` C++ API header](api/mdbx_8h_09_09.md)
Also in this section: [command-line tools](tooling.md).
Getting-started guidance lives in the [guides](../index.md); Getting-started guidance lives in the [guides](../index.md);
the [first steps](../getting-started/first-steps.md) page shows the canonical the [first steps](../getting-started/first-steps.md) page shows the canonical
......
...@@ -31,7 +31,6 @@ The full list of rules and tips is in the knowledge base (`knowledge-base/rules- ...@@ -31,7 +31,6 @@ The full list of rules and tips is in the knowledge base (`knowledge-base/rules-
- Set the geometry once before open; do not lower `upper`. - Set the geometry once before open; do not lower `upper`.
- Lower `rp_augment_limit` — only together with `gc_time_limit`. - Lower `rp_augment_limit` — only together with `gc_time_limit`.
- Do not use `MDBX_ENABLE_REFUND=0` in production (debug option).
- Long values: increase the page size (up to 64 KB), split records. - Long values: increase the page size (up to 64 KB), split records.
- A value spanning several overflow pages needs a run of **consecutive** pages: when large values are - A value spanning several overflow pages needs a run of **consecutive** pages: when large values are
rewritten often, watch fragmentation (`mdbx_chk` histograms, overflow page counts in rewritten often, watch fragmentation (`mdbx_chk` histograms, overflow page counts in
...@@ -84,7 +83,7 @@ Full code: [34-rules-counter.c++](examples/c++/34-rules-counter.c++). ...@@ -84,7 +83,7 @@ Full code: [34-rules-counter.c++](examples/c++/34-rules-counter.c++).
- One transaction — one thread: passing a transaction between threads is UB/an error (`MDBX_THREAD_MISMATCH`), even with `NOSTICKYTHREADS` a deadlock is possible. - One transaction — one thread: passing a transaction between threads is UB/an error (`MDBX_THREAD_MISMATCH`), even with `NOSTICKYTHREADS` a deadlock is possible.
- An unclosed read-transaction "freezes" page reclamation — the file grows to `MDBX_MAP_FULL`; close/park it. - An unclosed read-transaction "freezes" page reclamation — the file grows to `MDBX_MAP_FULL`; close/park it.
- Do not open the database twice in one process; `fork()` — only with `resurrect_after_fork` in the child; copying — only `mdbx_copy`. - Do not open the database twice in one process; `fork()` — only with `resurrect_after_fork` in the child; copying — only `mdbx_copy`.
- Do not use `MDBX_UTTERLY_NOSYNC` or debug options (`MDBX_ENABLE_REFUND=0`) in production. - Do not use `MDBX_UTTERLY_NOSYNC` in production.
- Set the geometry once before open, do not lower `upper`; for long values increase the page size (up to 64 KB), split into chunks that fit into one page, or store outside the DB; values that do not fit one page need a contiguous run and are sensitive to fragmentation — until the streaming API ("Streaming BLOBs") arrives. - Set the geometry once before open, do not lower `upper`; for long values increase the page size (up to 64 KB), split into chunks that fit into one page, or store outside the DB; values that do not fit one page need a contiguous run and are sensitive to fragmentation — until the streaming API ("Streaming BLOBs") arrives.
- Do deletions before insertions; mass deletions — `bunch_delete`/`delete_range`; DUPSORT deletion while iterating — two cursors. - Do deletions before insertions; mass deletions — `bunch_delete`/`delete_range`; DUPSORT deletion while iterating — two cursors.
- Typical counter-examples: violating thread discipline (`BAD_RSLOT`), double opening, a forgotten reader, a debug build in production. - Typical counter-examples: violating thread discipline (`BAD_RSLOT`), double opening, a forgotten reader, a debug build in production.
...@@ -95,7 +94,7 @@ Full code: [34-rules-counter.c++](examples/c++/34-rules-counter.c++). ...@@ -95,7 +94,7 @@ Full code: [34-rules-counter.c++](examples/c++/34-rules-counter.c++).
- [ ] Close/park read-transactions immediately after use. - [ ] Close/park read-transactions immediately after use.
- [ ] Copy the database file only via `mdbx_copy`. - [ ] Copy the database file only via `mdbx_copy`.
- [ ] Set the geometry before open and do not lower `upper`. - [ ] Set the geometry before open and do not lower `upper`.
- [ ] Exclude `MDBX_UTTERLY_NOSYNC` and `MDBX_ENABLE_REFUND=0` from production configuration. - [ ] Exclude `MDBX_UTTERLY_NOSYNC` from production configuration.
- [ ] Perform deletions before insertions; mass deletions — via `bunch_delete`/`delete_range`. - [ ] Perform deletions before insertions; mass deletions — via `bunch_delete`/`delete_range`.
- [ ] For DUPSORT deletion while iterating use two cursors. - [ ] For DUPSORT deletion while iterating use two cursors.
......
...@@ -209,7 +209,7 @@ libmdbx — как объект с собственным жизненным ц ...@@ -209,7 +209,7 @@ libmdbx — как объект с собственным жизненным ц
- **Диагностика GC**: `mdbx_gc_info()` (состояние, гистограммы, итерация записей) и счётчик - **Диагностика GC**: `mdbx_gc_info()` (состояние, гистограммы, итерация записей) и счётчик
`gcrtime` — время, потраченное на поиск и переработку. `gcrtime` — время, потраченное на поиск и переработку.
- **Refund/loose-страницы**: возврат освобождённых страниц внутри текущей транзакции без - **Refund/loose-страницы**: возврат освобождённых страниц внутри текущей транзакции без
обращения к GC (опции `MDBX_ENABLE_REFUND`, `MDBX_opt_loose_limit`, `dp_reserve_limit`). обращения к GC (опции `MDBX_opt_loose_limit`, `dp_reserve_limit`).
- **RKL** — отслеживание идентификаторов записей GC (интервалы + списки) с «резервированием - **RKL** — отслеживание идентификаторов записей GC (интервалы + списки) с «резервированием
со взвешенным запасом»: одно-проходное обновление GC с оценкой сложности от O(1) до O(log N). со взвешенным запасом»: одно-проходное обновление GC с оценкой сложности от O(1) до O(log N).
- **Разреженные и lock-free наборы DBI-хендлов** (`MDBX_ENABLE_DBI_SPARSE`, - **Разреженные и lock-free наборы DBI-хендлов** (`MDBX_ENABLE_DBI_SPARSE`,
......
# Шпаргалка по CRUD
> Смежные: [Первые шаги](first-steps.md) ·
> [Установка и сборка](install-build.md) ·
> [Учебник: Том I «Основы»](../textbook/01-tom-i-osnovy.md) ·
> [Справочник C API](https://libmdbx.dqdkfa.ru/docs/en/reference/api/group__c__api.html)
Компактная шпаргалка по наиболее частым операциям. Авторитетный
Quick Reference с полными таблицами решений генерируется из аннотаций
`mdbx.h` и расположен в справочнике C API:
- [Quick Reference для операций Insert/Update/Delete](https://libmdbx.dqdkfa.ru/docs/en/reference/api/group__c__crud.html) —
случаи для таблиц с UNIQUE-ключами и с NON-UNIQUE (DUPSORT) ключами, а также
соответствующие флаги (`MDBX_NOOVERWRITE`, `MDBX_UPSERT`, `MDBX_CURRENT`,
`MDBX_APPEND`, `MDBX_APPENDDUP`, ...).
## C++ API: кратко
C++-обёртка отображает C-операции на методы `mdbx::txn` и `mdbx::cursor`.
Наиболее употребимые:
| Операция | `mdbx::txn` | `mdbx::cursor` | Аналог в C |
|----------|-------------|----------------|------------|
| Вставить или вернуть ошибку | `insert(map, key, value)` | `insert(key, value)` | `mdbx_put(MDBX_NOOVERWRITE)` |
| Вставить или заменить | `upsert(map, key, value)` | `upsert(key, value)` | `mdbx_put(MDBX_UPSERT)` |
| Обновить существующее | `update(map, key, value)` | `update(key, value)` | `mdbx_put(MDBX_CURRENT)` |
| Прочитать | `get(map, key)` | `to_first()/to_find()/...` | `mdbx_get()` |
| Прочитать и удалить | `extract(map, key)` | — | `mdbx_replace()` |
| Удалить по ключу | `erase(map, key)` | `erase(key)` | `mdbx_del()` |
| Удалить пару | `erase(map, key, value)` | `erase(key, value)` | `mdbx_del()` |
| Добавить в конец | `put(map, key, value, MDBX_APPEND)` | `put(key, value, MDBX_APPEND)` | `mdbx_put(MDBX_APPEND)` |
> Подробнее — в [справочнике C++ API](https://libmdbx.dqdkfa.ru/docs/en/reference/api/classmdbx_1_1txn.html)
> и [классе `mdbx::cursor`](https://libmdbx.dqdkfa.ru/docs/en/reference/api/classmdbx_1_1cursor.html).
## Примеры
- [`examples/c++/03-crud.c++`](https://sourcecraft.dev/dqdkfa/libmdbx/blob?file=examples/c%2B%2B/03-crud.c%2B%2B) ·
[C версия](https://sourcecraft.dev/dqdkfa/libmdbx/blob?file=examples/c/03-crud.c)
- Учебник: [Глава 4. Базовые операции CRUD](../textbook/01-tom-i-osnovy.md)
## Читайте также
- [Первые шаги](first-steps.md) — минимальный цикл env → txn → dbi → get/put.
- [Режимы durability](durability-modes.md) — компромиссы между надёжностью и скоростью.
\ No newline at end of file
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
> Смежные: [Установка и сборка](install-build.md) · > Смежные: [Установка и сборка](install-build.md) ·
> [Тулинг](../reference/tooling.md) · [Ограничения](../overview/restrictions.md) · > [Тулинг](../reference/tooling.md) · [Ограничения](../overview/restrictions.md) ·
> [Учебник: Том I «Основы»](../textbook/01-tom-i-osnovy.md) · > [Учебник: Том I «Основы»](../textbook/01-tom-i-osnovy.md) ·
> [Шпаргалка CRUD](crud-quick.md) ·
> [Справочник C API](https://libmdbx.dqdkfa.ru/docs/en/reference/api/group__c__api.html) > [Справочник C API](https://libmdbx.dqdkfa.ru/docs/en/reference/api/group__c__api.html)
Всё начинается с **окружения** (`MDBX_env`): `mdbx_env_create()` → Всё начинается с **окружения** (`MDBX_env`): `mdbx_env_create()` →
...@@ -85,7 +86,8 @@ write: попытки начать следующую будут блокиро ...@@ -85,7 +86,8 @@ write: попытки начать следующую будут блокиро
- **Не используйте окружение в потомке после `fork()`** — libmdbx проверяет - **Не используйте окружение в потомке после `fork()`** — libmdbx проверяет
это в критических точках. При необходимости — это в критических точках. При необходимости —
`mdbx_env_resurrect_after_fork()`. `mdbx_env_resurrect_after_fork()`.
- **Не более одной транзакции на поток.** Нарушения детектируются кодами - **Не более одной транзакции на поток.** Транзакция привязана к потоку по
умолчанию (Thread Local Storage). Нарушения детектируются кодами
`MDBX_TXN_OVERLAPPING`, `MDBX_BAD_RSLOT`, `MDBX_BUSY` — если не включена `MDBX_TXN_OVERLAPPING`, `MDBX_BAD_RSLOT`, `MDBX_BUSY` — если не включена
опция `MDBX_NOSTICKYTHREADS` (передача транзакций между потоками; с ней опция `MDBX_NOSTICKYTHREADS` (передача транзакций между потоками; с ней
вы должны точно понимать, что делаете). Write-транзакция обязана быть вы должны точно понимать, что делаете). Write-транзакция обязана быть
...@@ -120,5 +122,13 @@ write: попытки начать следующую будут блокиро ...@@ -120,5 +122,13 @@ write: попытки начать следующую будут блокиро
- Оценка объёма диапазонных запросов: `mdbx_estimate_*`. - Оценка объёма диапазонных запросов: `mdbx_estimate_*`.
- Разрешение «БД заполнена» из-за долгих читателей: `mdbx_env_set_hsr()`. - Разрешение «БД заполнена» из-за долгих читателей: `mdbx_env_set_hsr()`.
- Последовательности и canary-маркеры: `mdbx_dbi_sequence()`, `MDBX_canary`. - Последовательности и canary-маркеры: `mdbx_dbi_sequence()`, `MDBX_canary`.
- Эксклюзивный режим: `MDBX_EXCLUSIVE`.
- Очистка БД: `mdbx_drop()`.
- Обнаружение и обработка ошибок: группа
[`c_err`](https://libmdbx.dqdkfa.ru/docs/en/reference/api/group__c__err.html).
- Статистика БД: группа
[`c_statinfo`](https://libmdbx.dqdkfa.ru/docs/en/reference/api/group__c__statinfo.html).
- Временное снижение надёжности ради скорости: [режимы долговечности](durability-modes.md).
- Пользовательские порядки сортировки (делать не рекомендуется).
- [Режимы долговечности](durability-modes.md) — компромиссы надёжность/скорость. - [Режимы долговечности](durability-modes.md) — компромиссы надёжность/скорость.
- [Учебник: Том I](../textbook/01-tom-i-osnovy.md) — систематическое изложение. - [Учебник: Том I](../textbook/01-tom-i-osnovy.md) — систематическое изложение.
...@@ -7,6 +7,9 @@ ...@@ -7,6 +7,9 @@
Выберите раздел: Выберите раздел:
- **[Журнал изменений](https://sourcecraft.dev/dqdkfa/libmdbx/browse/ChangeLog.md)** — новости
и последние обновления (ведётся на английском языке для удобства
международных пользователей).
- **[Обзор](overview/index.md)** — что такое libmdbx, характеристики, - **[Обзор](overview/index.md)** — что такое libmdbx, характеристики,
сравнение с альтернативами и когда его выбирать (плюс честный список сравнение с альтернативами и когда его выбирать (плюс честный список
[ограничений и подводных камней](overview/restrictions.md)). [ограничений и подводных камней](overview/restrictions.md)).
...@@ -17,8 +20,8 @@ ...@@ -17,8 +20,8 @@
томах, от первых шагов до экспертных тем и биндингов. томах, от первых шагов до экспертных тем и биндингов.
- **[Погружение](deep-dive/architecture.md)** — архитектура, внутренние - **[Погружение](deep-dive/architecture.md)** — архитектура, внутренние
механизмы и усовершенствования libmdbx относительно LMDB. механизмы и усовершенствования libmdbx относительно LMDB.
- **[Справочник](reference/index.md)** — справочник по C/C++ API, утилиты командной - **[Справочник](reference/index.md)** — справочник по C/C++ API и утилиты командной
строки и журнал изменений. строки.
Документация доступна на русском и английском — используйте языковую пилюлю Документация доступна на русском и английском — используйте языковую пилюлю
в правом верхнем углу любой страницы для переключения. в правом верхнем углу любой страницы для переключения.
Поддерживает Markdown
0% или .
You are about to add 0 people to the discussion. Proceed with caution.
Сначала завершите редактирование этого сообщения!
Пожалуйста, зарегистрируйтесь или чтобы прокомментировать