Skip to content

[Store] Fix CXL capacity metric leak on segment unmount - #2

Closed
stmatengss wants to merge 1 commit into
openanolis:hemist/cxl-level-storefrom
stmatengss:fix/cxl-metric-unmount-leak
Closed

stmatengss wants to merge 1 commit into
openanolis:hemist/cxl-level-storefrom
stmatengss:fix/cxl-metric-unmount-leak

Conversation

@stmatengss

Copy link
Copy Markdown

Problem

CommitUnmountSegment in segment.cpp only decrements capacity metrics for non-CXL segments:

if (!is_cxl) {
    dec_total_mem_capacity(segment_name, size);
    dec_total_dram_capacity(segment_name, size);
}
// CXL branch: nothing decremented ← bug

On mount, initializeCxlAllocator increments both inc_total_mem_capacity and inc_total_cxl_capacity. The unmount path never mirrors this for CXL, so the CXL capacity metric grows monotonically across remount cycles and never reflects actual capacity.

Fix

Add an else branch in CommitUnmountSegment that calls dec_total_mem_capacity and dec_total_cxl_capacity symmetrically with the mount path.

Impact

  • No behavior change for RAM segments
  • CXL capacity metrics now correctly reflect actual mounted capacity
  • Prevents metric inflation on CXL segment remount cycles

When a CXL segment is unmounted via CommitUnmountSegment, the total
capacity metrics were only decremented for non-CXL segments. CXL segments
never called dec_total_cxl_capacity, causing the metric to grow without
bound across remount cycles.

On mount (initializeCxlAllocator) both inc_total_mem_capacity and
inc_total_cxl_capacity are incremented. Match this symmetrically on unmount
by adding an else branch that calls both dec_total_mem_capacity and
dec_total_cxl_capacity for CXL segments.
@stmatengss
stmatengss requested review from XucSh and YiXR as code owners April 22, 2026 12:52
@stmatengss stmatengss closed this Apr 22, 2026
Bo-Vincent pushed a commit to Bo-Vincent/Mooncake that referenced this pull request Jul 21, 2026
Bo-Vincent pushed a commit to Bo-Vincent/Mooncake that referenced this pull request Jul 23, 2026
kvcache-ai#3029)

* [TENT] Add transport labels to metrics for per-transport observability

Switch all 16 TENT metrics from static to dynamic yalantinglibs types to
add a `transport` label (and `from`/`to` on the failover counter), so
operators can slice read/write bytes, requests, failures, latency, and
failover paths by transport without grepping logs.

Cardinality control: label values come exclusively from the TransportType
enum closed set (11 values) via a pre-built lookup table indexed by enum.
No arbitrary strings are accepted — the closed set is enforced at the type
level. Total series upper bound ~1500, fully bounded.

Changes:
- 7 counters + 8 histograms → basic_dynamic_counter/histogram<int64_t, 1>
  with label "transport"; failover counter → <int64_t, 2> with "from"/"to"
- counters_ vector widened to metric_t* base pointers (N varies 1 vs 2)
- All record methods take TransportType; 10 call sites in
  transfer_engine_impl.cpp migrated (9 in recordTaskCompletionMetrics +
  1 failover)
- Macros and ScopedLatencyRecorder updated with transport parameter
- getSummaryString()/getJsonMetrics() sum across labels for flat totals;
  per-transport breakdown available only via Prometheus /metrics
- Label values aligned with TransportSelector::transportTypeName()

Workaround: ylt basic_dynamic_histogram::serialize() calls str.clear()
when all label combos have sum=0, wiping previously serialized content.
Each metric is serialized into a temp buffer then appended to avoid this.
ylt upstream is not modified.

Also fixes pre-existing bug: shutdown() did not reset bound_http_port_,
so httpPort() returned a stale port after a shutdown+reinitialize cycle.

Verified: full build (USE_TENT=ON, TENT_METRICS_ENABLED=ON) clean;
metrics_config_loader_test 25/25, tent_metrics_http_server_test 1/1,
tent_metrics_recording_test 10/10; label landing confirmed via real
TransferEngine path with {transport="tcp"} in Prometheus output.

Signed-off-by: staryxchen <staryxchen@tencent.com>

* docs(tent/metrics): document transport labels and per-transport queries

Add Labels column to the Available Metrics table, a new Labels subsection
explaining the TransportType closed-set scheme (11 values, from/to on
failover, cardinality bounds), and update the Prometheus example output
and Grafana queries to show per-transport filtering.

Signed-off-by: staryxchen <staryxchen@tencent.com>

* Address review: fix initialize() regression + add bounds-checked label lookup

1. initialize() regression fix: the rebase inadvertently reverted task#1's
   fix (commit 7dc87d8) that moved validateConfig before compare_exchange.
   The old order (CAS first, validate second, reset on failure) had a race
   window where concurrent callers see initialized_=true and return OK
   against an unconfigured singleton. Restored the correct order: validate
   first, CAS second, no reset needed.

2. Bounds-checked label lookup: added transportLabel(TransportType) helper
   that returns "unknown" if tp is out of range, replacing 9 direct
   kTransportLabelNames[tp] accesses. Defensive guard against memory
   corruption or a new transport type added without updating the table.

Addresses gemini-code-assist review feedback on PR kvcache-ai#3029 (items openanolis#1 high,
openanolis#2 medium). Item openanolis#3 (null check in sumCounterValues) intentionally not
addressed — the pointers are class members, not dynamically allocated.

Signed-off-by: staryxchen <staryxchen@tencent.com>

* Address review: fix docs code examples + add per-transport label test

M1: Update "Recording Transfer Metrics" and "RAII Latency Measurement"
code examples in metrics.md to use the new API signatures with
TransportType parameter. The old examples would not compile.

M2: Add PrometheusLabelsDistinguishTransports test that records with
RDMA and TCP transports, scrapes /metrics, and asserts per-transport
labels appear as separate lines plus from/to labels on the failover
counter.

Addresses general-purpose-6 review feedback on PR kvcache-ai#3029.

Signed-off-by: staryxchen <staryxchen@tencent.com>

* trigger CI with run-ci label

* Fix CI: guard kTransportLabelNames definition with TENT_METRICS_ENABLED

The definition was outside the #if TENT_METRICS_ENABLED block, so
building with TENT_METRICS_ENABLED=0 (the CI default) failed because
the declaration (inside #if in the header) was not visible. Moved the
definition inside the #if block.

Signed-off-by: staryxchen <staryxchen@tencent.com>

---------

Signed-off-by: staryxchen <staryxchen@tencent.com>
Bo-Vincent pushed a commit to Bo-Vincent/Mooncake that referenced this pull request Nov 2, 2026
…B contexts (kvcache-ai#5104)

* [TransferEngine] Fix URMA module lifecycle for multi-device UB contexts

urma_init()/urma_uninit() are process-global, but the UB transport paired
them wrongly: UrmaContext::deconstruct() called urma_uninit() once per
context, while UbTransport::init() called urma_init() once per transport and
~UbTransport() never released it.

With a single device the extra uninit() was harmless. With two or more devices
the first context destructor released the whole URMA module while sibling
contexts still held jetties, and the next teardown faulted:

  #0 urma_unbind_jetty ()
  openanolis#1 UrmaEndpoint::deconstruct()      urma_endpoint.cpp:680
  openanolis#2 UbSIEVEEndpointStore::destroy()  ub_context.cpp:145
  openanolis#3 UrmaContext::~UrmaContext()
  kvcache-ai#16 UbTransport::~UbTransport()

Reproduced on a Kunpeng 950 host with 10 URMA devices: any target or initiator
configured with two devices crashed on exit while the same single-device
configuration ran fine.

Let the transport own the module lifetime: drop the per-context uninit(),
record whether init() ran, make uninit() idempotent, and pair init() in the
destructor after the contexts are gone. install() failure paths already call
uninit(), so the guard keeps those from releasing the module twice.

* [TransferEngine] Do not dereference a null URMA context while logging

UbContext::doConstruct() reports a construction failure with

  LOG(INFO) << "failed construct context " << toString();

and UrmaContext::toString() calls getAsyncFd(), which dereferenced
urma_context_ unconditionally. Opening a device can fail - for example when no
configured device name matches, or the mock build is used on a host with real
URMA devices - so the failure was reported as a SIGSEGV instead of an error.

Return -1 when the context has not been created so the existing error path
survives long enough to log and return ERR_DEVICE_NOT_FOUND.

* [TransferEngine] Fix a data race in UrmaContext::retrieveRemoteSeg

retrieveRemoteSeg() is reached from every submitting thread through
UbWorkerPool::submitPostSend(), but it did its cache lookup, malloc and
push_back into remote_seg_list_ with no synchronisation. Two threads that both
miss the cache therefore push concurrently, and when the vector reallocates
both free the old buffer: AddressSanitizer reports

  ERROR: AddressSanitizer: attempting double-free
  openanolis#7 UrmaContext::retrieveRemoteSeg()   urma_endpoint.cpp:364
  openanolis#9 UbWorkerPool::submitPostSend()     ub_context.cpp:271

After the corruption a later malloc()/free() segfaults somewhere unrelated,
which is what a multi-initiator benchmark sees as a random SIGSEGV.

The same function also published the handle in remote_seg_list_ before the
import succeeded, so a failed urma_import_seg() left it for deconstruct() to
free a second time.

Guard the map and the lists with a shared_mutex: shared lock for the hot
lookup path, unique lock for publishing, with a second lookup so a thread that
lost the race drops its own import. Publish only after a successful import.

Verified with four concurrent initiators (2 read + 2 write, 2 devices,
64 KiB blocks) under ASan: before the fix 3 of 8 processes reported a
double-free, after it 8 of 8 are clean across repeated runs, and the
non-instrumented build finishes 5 mixed scenarios with no crash.

* ci: retrigger build (previous run was cancelled by a runner shutdown)

* [TransferEngine] Read the UB device NUMA node from ubcore sysfs

UbContext::socketId() built its path from /sys/class/infiniband/<dev>/device/numa_node.
URMA devices have no infiniband entry, so the lookup always failed and every
UbWorkerPool thread was pinned to node 0 via bindToSocket() regardless of where
the device actually sits.

The node is published two directories above the /sys/class/ubcore/<dev> link,
next to the ub_bus_controller directory, and is formatted as hex (0x01), so a
plain '>> int' would have truncated it to 0 even with the right path.

Resolve the link with realpath(), walk two levels up, and parse the value with
base 0 so the hex form is handled.

On a 4-node Kunpeng 950 (node 0: CPU 0-95, node 1: 96-191, node 2: 192-287,
node 3: 288-383) with udmac1d1e2, which reports numa=0x03:

  before: 3 worker threads Cpus_allowed_list=0-95
  after:  3 worker threads Cpus_allowed_list=288-383

Devices udmac0* report 0x01 and udmac1* report 0x03, so the two device groups
are now pinned to their own nodes instead of both landing on node 0.

* docs: correct the device-name comments in UbContext

The deviceName()/nicPath() comments were copied from the RDMA transport and
still said 'mlx5_3'. URMA devices are named after their ubcore entry
(udmac0d1e2, udmac1d1e6, ...) and the NIC path is '${server}:${port}@${device}',
for example 127.0.0.1:15479@udmac0d1e3.

* docs: point the mock URMA device path at ubcore sysfs

mock_urma.cpp advertised /sys/class/infiniband/mock_device, which does not
exist for any UB device. Nothing reads urma_device_t::path (listUBDevices()
builds /sys/class/ubcore/<name> from the device name), so this was dead data,
but it kept the RDMA spelling that misleads readers of the UB transport.

Verified the mock build still compiles and passes:
  cmake .. -DUSE_UB=ON -DURMA_LIBRARY= ...   # 'building ub_transport with Mock URMA library'
  ./ub_transport_test --metadata_server=P2PHANDSHAKE ...
  [  PASSED  ] 2 tests.

* docs: call the UB endpoint a device, not an RNIC

Two diagnostics in the UB worker pool reported problems on a 'local RNIC'.
UB has no NIC; the value logged next to the message is nicPath(), i.e.
<host>:<port>@<ubep device>, so 'local UB device' describes it accurately.

The '<Transport>: No available RNIC' messages in rdma/barex/ub are left
untouched: that sentence is deliberately shared across transports.

Both builds still compile and the mock UB test passes:
  make -j64 transfer_engine_bench        -> 0 errors
  make -j64 ub_transport_test (mock)     -> 0 errors
  ./ub_transport_test                    -> [  PASSED  ] 2 tests
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant