Repository navigation
Refactor settings: remove vtable, simplify boilerplate - #102269
Conversation
|
Workflow [PR], commit [81dc999] Summary: ❌
AI ReviewSummaryThis PR refactors settings internals to replace per-setting virtual dispatch with type-erased per-type ops, introduces Final VerdictStatus: ✅ Approve |
Replace per-setting virtual dispatch with a shared `SettingFieldOps` function-pointer table (one per type, not per setting) and a constexpr typed-array layout that groups settings by type into contiguous arrays. This applies to ALL settings types (Settings, MergeTreeSettings, ServerSettings, etc.), not just the main Settings class. Key changes: **SettingFieldOps** (`SettingsFields.h`): A struct of 11 function pointers for type-erased operations (assign, to_field, to_string, parse, serialize, etc.). One static instance per SettingField type via `settingFieldOps<T>()`. Replaces per-setting vtable pointers. **SettingIndex** (`SettingIndex.h`): A typed byte offset replacing pointer-to-member for compile-time-safe setting access. **Constexpr typed-array layout** (`BaseSettings.h`): `DECLARE_SETTINGS_TRAITS` now takes a `SUPPORTED_TYPES` macro and generates at compile time: - `SettingTypeTag` enum and `SettingID` enum - `SettingsLayout` with per-type array sizes and per-setting local indices - `Data` struct with typed arrays (e.g., `Bool_[]`, `UInt64_[]`) - A single `getSettingDefault_` switch function (replacing 1500 per-setting lambdas, cutting Settings.cpp compile time by ~13%) - Default-value constructor **Trivially-copyable fields** (`SettingsFields.h`): Defaulted copy constructors/operators for all SettingField types, making numeric and enum types trivially copyable. This halves the Data copy constructor size (7 KB → 3.4 KB for Settings). **BaseSettings operator[]**: Added `SettingIndex<T>`-based subscript operators to `BaseSettings`, replacing pointer-to-member access. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Add an Owner template parameter to SettingIndex<Owner, FieldType> so that e.g. SettingIndex<Settings, SettingFieldBool> is a different type from SettingIndex<MergeTreeSettings, SettingFieldBool>. This makes cross-class index misuse a compile error. Forward-declare each settings struct before its DECLARE_SETTING_TRAIT usage so the Owner type is available as a template argument. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Store `Poco::Timespan::TimeDiff` (int64_t) instead of `Poco::Timespan` in `SettingFieldTimespan`. Poco::Timespan has user-defined copy/dtor that prevent trivial copyability despite wrapping a single int64_t. This makes 46 settings (22 Seconds + 28 Milliseconds fields across Settings alone) trivially copyable, enabling the compiler to include them in the memcpy prefix of the Data copy constructor. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
IMPLEMENT_SETTINGS_TRAITS now generates the Impl struct, Data constructor, Accessor singleton, and Setting::NAME extern variables in one macro call. This removes ~15 lines of repetitive boilerplate per settings class (SETTINGS_DATA_BASE_OFFSET_, INITIALIZE_SETTING_EXTERN macro, namespace block, #undef). The forward declaration of the owner class (needed for the SettingIndex template tag) is now embedded in DECLARE_SETTING_TRAIT and IMPLEMENT_SETTINGS_EXTERN_, eliminating the need for manual forward declarations in each header. Variants: - IMPLEMENT_SETTINGS_TRAITS: standard (generates Impl struct) - IMPLEMENT_SETTINGS_TRAITS_CUSTOM_IMPL: Impl defined externally - IMPLEMENT_SETTINGS_TRAITS_WITH_PATH_CUSTOM_IMPL: with config paths Also made SettingFieldTimespan trivially copyable by storing raw int64_t microseconds instead of Poco::Timespan. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- IMPLEMENT_SETTINGS_TRAITS now generates Impl struct, Data constructor, Accessor singleton, and Setting::NAME extern variables in one call, removing ~15 lines of boilerplate per settings class. - Forward declaration of the owner class is embedded in DECLARE_SETTING_TRAIT and IMPLEMENT_SETTINGS_EXTERN_, eliminating manual forward declarations. - Made SettingFieldTimespan trivially copyable by storing raw int64_t microseconds instead of Poco::Timespan. - Removed SettingFieldBase empty base class — it was the pre-vtable-removal polymorphic base, now unused since dispatch goes through SettingFieldOps. - Updated BaseSettings.h example to match new macro signatures. - Added comments explaining WHY the constexpr layout exists and WHY helper macros use Traits_/Owner_ aliases. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
f375950 to
80014ff
Compare
|
There is a speed up in faster queries. This was not intended, as I just wanted to make the code smaller and less heavy, but it's nice to see: |
…able-v2 # Conflicts: # src/Storages/MergeTree/MergeTreeSettings.cpp
6383a00 to
09ec27c
Compare
…able-v2 # Conflicts: # src/Core/BaseSettings.h # src/Core/SettingsFields.h
Master added `SettingFieldBase::resetFromDefault` (issue ClickHouse#103120, PR ClickHouse#103991) to preserve `SettingFieldMaxThreads::is_auto` across `SET <name> = DEFAULT`, which the previous `Field` round-trip in `BaseSettings::resetValueToDefault` dropped because `SettingFieldMaxThreads::operator Field` is non-invertible. This branch removed `SettingFieldBase` entirely, so the override mechanism doesn't apply. Equivalent fix without virtuals: keep one default-constructed `Data` instance per `Accessor` (no per-setting cost) and reset individual settings via a per-type `typed_copy` function pointer in `SettingFieldOps` that does `*static_cast<T *>(dst) = *static_cast<const T *>(src)`. The defaulted copy assignment of `SettingFieldMaxThreads` preserves all members including `is_auto`, so the regression test `04202_set_default_preserves_max_threads_auto` passes without any per-setting code. The cached default `Data` also lets `getDefaultValueString` read directly through the existing `to_string` op, replacing the per-setting `getSettingDefault_` switch and the `default_fn_` / `default_index_` fields in `FieldInfo` (16 B × ~2k settings ≈ 32 KB removed from the `Settings` accessor singleton). Also rename the `sf*` short helpers in `SettingsFields.h` to spelled-out `settingField*` names.
`BaseSettings<Traits>` (and therefore `Settings`, `MergeTreeSettings`, etc.)
inherits from `Traits::Data` and is `BaseSettings() = default`, so every
fresh construction ran `Data::Data()` — a per-setting init function that
expands once for every declared setting. For `Settings` this is ~86 KB of
generated instructions per call.
Now the per-setting init lives in a private tag-based ctor
`Data(DefaultInitTag)` that is invoked exactly once, when the
`Accessor::default_data` member is initialized during singleton
construction. The public `Data::Data()` becomes a typed copy from that
canonical instance (~1.3 KB for `Settings`, scaled by `sizeof(Data)`),
i.e. the same code path as `Settings(const Settings &)`.
The tag has an explicit default ctor so callers can't synthesize it with
`{}`, keeping the raw-init path internal to the macro expansion.
|
Recent changes
|
`BaseSettings::operator[]` previously took `SettingIndex<Owner, FieldType>` with `Owner` as an unconstrained template parameter, so a `SettingIndex` from a different settings class (e.g. `MergeTreeSetting::name` applied to a `SettingsImpl`) would still match and apply the offset as raw byte arithmetic against the wrong object layout. The PR description claimed compile-time cross-class safety, but the catch-all overload didn't enforce it. Add a `SettingsOwner<Traits>` trait template (primary undefined, specialized once per settings class in `IMPLEMENT_SETTINGS_EXTERN_`). The operator[] body now `static_assert`s that the deduced `Owner` matches `SettingsOwner<TTraits>::type`. Keeping the check in the body (not the signature) means the specialization only needs to be visible at the call site, not at the point each `BaseSettings<Traits>` class is instantiated - which avoids a chicken-and-egg with the `struct *Impl : BaseSettings<Traits>` declaration that triggers class instantiation before the IMPLEMENT macro runs. A cross-class call now hard-fails with "SettingIndex belongs to a different settings class than this BaseSettings", zero runtime cost for valid uses.
`settingsDataBaseOffset` computed the Impl->Data subobject distance by
forging a pointer:
const Impl * fake = reinterpret_cast<const Impl *>(alignof(Impl));
const auto * data = static_cast<const Data *>(fake);
return reinterpret_cast<const char *>(data) - reinterpret_cast<const char *>(fake);
`static_cast<Data *>` on a derived pointer that doesn't point at a real
Impl is undefined behavior (`[expr.static.cast]/11`). Clang happens to
fold it to layout arithmetic today, but a more aggressive optimizer (or
LTO / a future toolchain bump) could assume the UB cannot occur and emit
a wrong constant, silently corrupting every `SettingIndex`-based read or
write.
Switch to storing `SettingIndex` offsets relative to `Traits::Data` (not
Impl) and let the operator[] overloads do the derived-to-base conversion
on a real `this`, where the cast is fully defined:
auto * data = static_cast<typename TTraits::Data *>(this);
return *reinterpret_cast<FieldType *>(reinterpret_cast<char *>(data) + offset);
`BaseSettings::operator[]`, the wrapper-class subscript generated by
`IMPLEMENT_SETTING_SUBSCRIPT_OPERATOR`, and the local `IMPL_SUBSCRIPT_OP_`
inside `MergeTreeSettingsImpl` all funnel through this single path.
Without this last step a wrapper subscript would silently land on the
wrong field (an earlier iteration of this commit missed it, and the
server crashed at start because `remap_executable` was being read as a
non-zero byte).
`settingsDataBaseOffset`, the `DATA_BASE_OFFSET_` static, and the
`IMPL_TYPE` parameter on the `IMPLEMENT_SETTINGS_EXTERN_*` macros are all
gone. Also drops two vestigial `NOLINT(misc-use-internal-linkage)` hints
on a forward declaration and a namespace block that don't actually
trigger the check.
Assembly for representative hot paths (`MergeTreeSettingsImpl::sanityCheck`,
`MergeTreeSettingsImpl::loadFromQuery`) is identical in shape; the
extra adjustment is a single `add`. Symbol sizes for `Settings::Data`
ctors match the PR description within rounding.
`DECLARE_SETTINGS_TRAITS_COMMON` previously declared `SettingTypeTag`, `SettingID`, `SettingsLayout`, `setting_type_tags`, `computeSettingsLayout`, and `settings_layout` at namespace scope under fixed names. Every settings `.cpp` expanded the macro and redefined those entities with different contents under the same `DB::SettingTypeTag` / `DB::settings_layout` / etc. names - a textbook ODR violation, even though each TU only ever sees its own copy. Put them in a per-traits namespace `SETTINGS_TRAITS_NAME##Detail` so the qualified names are unique across .cpp files (`SettingsTraitsDetail::SettingTypeTag` vs `MergeTreeSettingsTraitsDetail::SettingTypeTag`, etc.). The Traits struct's existing `_`-suffixed aliases now point into that namespace, so downstream macros (`SETTING_INIT_DEFAULT_`, `SETTING_EXTERN_ENTRY_`, `Accessor::resetValueToDefault`, `getDefaultValueString`) compile unchanged. Only `SETTING_DECLARE_DATA_ARRAY_`, used directly inside the nested `Data` struct, needed `CLASS_NAME##Detail::` qualification. Nesting these helpers as `static constexpr` members inside the Traits struct would have been an alternative but hits the deferred-parsing rule for in-class member function bodies and nested-type default member initializers - `settings_layout = computeSettingsLayout()` is not a constant expression at that point. The per-traits namespace avoids that without complicating the macro further. Sizes after the change: - `Settings::Data::Data(const Data &)`: 1,359 B / 271 instr (unchanged) - `Settings::Data::Data(DefaultInitTag)`: ~86 KB (was ~86 KB; +1.1%) - `MergeTreeSettings`, `ServerSettings`, etc.: all byte-identical. - `DB::Settings` / `DB::SettingFieldOps`: unchanged.
…Index offset
- `SettingFieldTimespan::microseconds` and the helper casts/return types in
`SettingsFields.{h,cpp}` were typed as `Poco::Timespan::TimeDiff` only because
the field used to wrap a `Poco::Timespan`. The recent commit that switched to
raw microseconds left the Poco-flavored alias in place. The underlying type
has always been `Int64`; drop the indirection. `Poco::Timespan` still appears
in the public interface (the implicit conversion and the constructor /
assignment from it), so the include is unchanged.
- `SettingIndex::offset` is now defaulted to `static_cast<size_t>(-1)` instead
of being uninitialized. The previous behavior would have silently aliased
the first field of `Data` at offset `0` for any `SettingIndex` that escaped
brace-initialization; the sentinel turns that into an immediate out-of-bounds
crash rather than a quiet wrong-field access. Legitimate uses always go
through `SETTING_EXTERN_ENTRY_`'s brace-init, so the default value is only
ever observed by accident.
Verified end-to-end: `SET <name> = {int, float, large}` round-trips through
`system.settings` and `getSetting()` for both `Seconds` (`connect_timeout`)
and `Milliseconds` (`sleep_in_send_data_ms`) settings; `SET <name> = DEFAULT`
restores typed defaults; per-query `SETTINGS` overrides apply without
polluting the session; `max_execution_time = 0.01` fires at ~10 ms (proving
the `Float64-seconds → Int64-microseconds → runtime compare` path is intact).
LLVM Coverage Report
Changed lines: 81.18% (509/627) | lost baseline coverage: 36 line(s) · Uncovered code |
c5937c4

Supersedes #101228.
Refactor of the settings infrastructure (
Settings,MergeTreeSettings,ServerSettings, etc.) to remove per-setting virtual dispatch and simplify the boilerplate around declaring a settings class.SettingFieldOps: A struct of 12 function pointers for type-erased operations (assign, to_field, to_string, parse, serialize, typed_copy, etc.). One static instance per setting type — not per setting — replacing the per-setting vtable pointers.SettingIndex<Owner, T>: A typed, owner-aware byte offset replacing pointer-to-member for compile-time-safe setting access. TheOwnertag prevents cross-class index misuse at compile time (e.g. passing aSettingsBooltoMergeTreeSettings::operator[]is a type error).Constexpr typed-array layout:
DECLARE_SETTINGS_TRAITSnow takes aSUPPORTED_TYPESmacro and generates at compile time: type tag enum, setting ID enum,SettingsLayoutwith per-type array sizes and per-setting local indices,Datastruct with typed arrays (e.g.Bool_[],UInt64_[]), and per-setting init constructor.Trivially-copyable fields: Defaulted copy constructors/operators for all
SettingFieldtypes.SettingFieldTimespanstores rawint64_tmicroseconds instead ofPoco::Timespan(which has user-defined copy/dtor despite wrapping a single int64_t), making all 46Seconds/Millisecondssettings trivially copyable.Cached default
Data+ typed copy: EachAccessorsingleton holds one canonical default-constructedDatainstance, populated once via a private tag-based ctor that runs the per-setting init.Data::Data()(called by every freshSettings()construction) becomes a typed copy from this singleton.resetValueToDefaultandgetDefaultValueStringlikewise read through it via the type-erasedtyped_copy/to_stringops. This eliminates the per-settinggetSettingDefault_switch that previously had ~2k cases forSettings(and thedefault_fn_/default_index_per-setting fields, ~32 KB of accessor metadata removed). It also fixes issue #103120 (SET <name> = DEFAULTlosingSettingFieldMaxThreads::is_auto): the typed copy preserves all members, where the previousFieldround-trip dropped non-invertible state.Unified
IMPLEMENT_SETTINGS_TRAITSmacros: Now generate theImplstruct,Dataconstructor,Accessorsingleton, andSetting::NAMEextern variables in one macro call, removing ~15 lines of repetitive boilerplate per settings class. The forward declaration of the owner class is embedded inDECLARE_SETTING_TRAITandIMPLEMENT_SETTINGS_EXTERN_, eliminating manual forward declarations. Variants:IMPLEMENT_SETTINGS_TRAITS(standard),IMPLEMENT_SETTINGS_TRAITS_CUSTOM_IMPL(Impldefined externally),IMPLEMENT_SETTINGS_TRAITS_WITH_PATH_CUSTOM_IMPL(with config paths).Per-construction code size for
Settings:Data::Data()(default ctor)Data::Data(const Data &)(copy ctor)Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Remove vtable from setting field types, reducing
Settingscopy size by ~28x and improving cache locality via typed-array layout for all settings types.Documentation entry for user-facing changes
Version info
26.5.1.681