This is an automated email from the ASF dual-hosted git repository.

CurtHagenlocher pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-adbc.git


The following commit(s) were added to refs/heads/main by this push:
     new 248eadaa19 feat(csharp): collect garbage when an exported driver goes 
idle (#4917)
248eadaa19 is described below

commit 248eadaa19db3f572fad9bf187030125b3533a91
Author: Curt Hagenlocher <[email protected]>
AuthorDate: Sun Oct 18 08:44:57 2026 -0700

    feat(csharp): collect garbage when an exported driver goes idle (#4917)
    
    ## What's changed
    
    A driver published with NativeAOT gets its own GC heap, and the runtime
    only collects that heap in response to allocations. Nothing collects it
    on a timer, and the low-memory notification doesn't collect an idle heap
    either. So once a caller releases its databases, the memory the driver
    last used stays committed for the rest of the process's life.
    
    `CAdbcDriverExporter` now counts the databases it has open. A collection
    is scheduled when the last database is released, or when the driver is
    released while no databases are open. It runs on a thread-pool thread
    after `IdleCollectionDelay`, and only if no database was opened in the
    meantime. The collection is `Collect` + `WaitForPendingFinalizers` + an
    aggressive, compacting gen2 collection.
    
    - `IdleCollectionDelay` is a new public static `TimeSpan?`, and `null`
    turns the feature off.
    - It defaults to one second when running under NativeAOT
    (`!RuntimeFeature.IsDynamicCodeSupported`). It defaults to `null` under
    JIT, where the driver shares its heap with the host, and on the
    `netstandard2.0` build.
    - Waiting for finalizers is needed for now because exported record
    batches are freed by their finalizers rather than when the consumer
    releases them (apache/arrow-dotnet#464).
    - A plain `GC.Collect()` empties the heap but leaves the memory
    committed. `GCCollectionMode.Aggressive` decommits it.
    
    ### Measurements
    
    A NativeAOT driver built on the exporter was loaded by a C host, which
    ran a workload and then released everything. The host never asks for a
    collection. Numbers are process private bytes; the baseline is about 3
    MB.
    
    | Workload | After release | 10 s later, with this change |
    |---|---|---|
    | 2 × 6 batches × 4M rows | 419 MB | 5.9 MB |
    | 3 × 50 batches × 64K rows | 24.5 MB | 4.4 MB |
    
    Without this change, the 64K-row run was sampled every 10 s for 60 s
    after release, and its memory never went down.
    
    The forced collection took 2–32 ms in these runs.
    
    ### NativeAOT workaround
    
    `AdbcDriverInit` now evaluates `Encoding.UTF8` on the caller's thread.
    Starting the idle timer starts a thread in the driver's runtime, and on
    Linux that can hit a NativeAOT bug that fails the process fast
    (dotnet/runtime#136031). The thread runs `UTF8Encoding`'s static
    constructor while it sets its name, and if it contends on another type's
    constructor lock at that moment, `Lock`'s statics initialization
    re-enters the encoding while its static instance is still null. Without
    the workaround, the AOT fixture tests crashed on every run on Linux.
    
    ### Tests
    
    `IdleCollectorTests` covers:
    - collecting after the last database is released;
    - collecting only once when the driver is released after the databases;
    - skipping when a database is reopened during the delay;
    - collecting again after a later idle period;
    - disabling with a `null` delay, and rejecting a negative delay;
    - the JIT default.
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    ---------
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 .../src/Apache.Arrow.Adbc/C/CAdbcDriverExporter.cs |  61 ++++++++
 .../src/Apache.Arrow.Adbc/C/CAdbcDriverImporter.cs |   3 +-
 csharp/src/Apache.Arrow.Adbc/C/IdleCollector.cs    | 118 ++++++++++++++
 .../Apache.Arrow.Adbc.Tests/IdleCollectorTests.cs  | 170 +++++++++++++++++++++
 4 files changed, 351 insertions(+), 1 deletion(-)

diff --git a/csharp/src/Apache.Arrow.Adbc/C/CAdbcDriverExporter.cs 
b/csharp/src/Apache.Arrow.Adbc/C/CAdbcDriverExporter.cs
index 8edd66a257..90c12346a1 100644
--- a/csharp/src/Apache.Arrow.Adbc/C/CAdbcDriverExporter.cs
+++ b/csharp/src/Apache.Arrow.Adbc/C/CAdbcDriverExporter.cs
@@ -44,6 +44,57 @@ namespace Apache.Arrow.Adbc.C
         /// </summary>
         internal const int ErrorVendorCodePrivateData = int.MinValue;
 
+        private static readonly IdleCollector s_idleCollector = new 
IdleCollector(CollectGarbage, DefaultIdleCollectionDelay());
+
+        /// <summary>
+        /// Gets or sets how long the exporter waits, after the last database 
has been released,
+        /// before it forces a full, compacting garbage collection; or 
<c>null</c> to never force one.
+        /// </summary>
+        /// <remarks>
+        /// <para>A driver published with NativeAOT has a garbage-collected 
heap of its own, and
+        /// the runtime only collects it in response to allocations. Once a 
caller has released
+        /// all of its databases, the driver stops allocating and the memory 
it last used stays
+        /// committed for the life of the process. Forcing a collection once 
the driver is idle
+        /// returns that memory to the operating system. The collection runs 
on a thread-pool
+        /// thread, and only if no database has been opened in the 
meantime.</para>
+        /// <para>The default is one second when the driver is compiled with 
NativeAOT, and
+        /// <c>null</c> otherwise, because a JIT-compiled driver shares its 
heap with the host.</para>
+        /// <para>A collection that is still pending when the driver is 
released runs after
+        /// the release returns. A driver that expects its host to unload it 
after releasing it
+        /// should set this to <c>null</c>, although unloading a NativeAOT 
library isn't
+        /// supported in any case.</para>
+        /// </remarks>
+        /// <exception cref="ArgumentOutOfRangeException">The value is 
negative or longer than
+        /// <see cref="int.MaxValue"/> milliseconds.</exception>
+        public static TimeSpan? IdleCollectionDelay
+        {
+            get => s_idleCollector.Delay;
+            set => s_idleCollector.Delay = value;
+        }
+
+        private static TimeSpan? DefaultIdleCollectionDelay()
+        {
+#if NET7_0_OR_GREATER
+            return 
System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported ? null : 
TimeSpan.FromSeconds(1);
+#else
+            return null;
+#endif
+        }
+
+        private static void CollectGarbage()
+        {
+            // Exported Arrow buffers are currently freed by their finalizers 
rather than when the
+            // consumer releases them (apache/arrow-dotnet#464), so run those 
before compacting.
+            GC.Collect();
+            GC.WaitForPendingFinalizers();
+#if NET7_0_OR_GREATER
+            GC.Collect(GC.MaxGeneration, GCCollectionMode.Aggressive, 
blocking: true, compacting: true);
+#else
+            System.Runtime.GCSettings.LargeObjectHeapCompactionMode = 
System.Runtime.GCLargeObjectHeapCompactionMode.CompactOnce;
+            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: 
true, compacting: true);
+#endif
+        }
+
         private static unsafe readonly NativeDelegate<ErrorRelease> 
s_releaseError = new NativeDelegate<ErrorRelease>(ReleaseError);
 
 #if NET5_0_OR_GREATER
@@ -183,6 +234,13 @@ namespace Apache.Arrow.Adbc.C
                 return AdbcStatusCode.NotImplemented;
             }
 
+            // Under NativeAOT on Linux, a thread that runs UTF8Encoding's 
static constructor and
+            // contends on another type's constructor lock re-enters it while 
initializing Lock,
+            // finds the encoding still null, and fails fast. A newly started 
thread does this
+            // when it sets its name, so run it here, before the exporter 
starts any threads.
+            // See https://github.com/dotnet/runtime/issues/136031.
+            _ = Encoding.UTF8;
+
             DriverStub stub = new DriverStub(driver);
             GCHandle handle = GCHandle.Alloc(stub);
             nativeDriver->private_data = (void*)GCHandle.ToIntPtr(handle);
@@ -424,6 +482,7 @@ namespace Apache.Arrow.Adbc.C
                 stub.Dispose();
                 gch.Free();
                 nativeDriver->private_data = null;
+                s_idleCollector.DriverReleased();
                 return AdbcStatusCode.Success;
             }
             catch (Exception e)
@@ -537,6 +596,7 @@ namespace Apache.Arrow.Adbc.C
                 stub.Dispose();
                 gch.Free();
                 nativeDatabase->private_data = null;
+                s_idleCollector.DatabaseReleased();
                 return AdbcStatusCode.Success;
             }
             catch (Exception e)
@@ -1673,6 +1733,7 @@ namespace Apache.Arrow.Adbc.C
                     DatabaseStub stub = new DatabaseStub(_driver);
                     GCHandle handle = GCHandle.Alloc(stub);
                     nativeDatabase->private_data = 
(void*)GCHandle.ToIntPtr(handle);
+                    s_idleCollector.DatabaseOpened();
                     return AdbcStatusCode.Success;
                 }
                 catch (Exception e)
diff --git a/csharp/src/Apache.Arrow.Adbc/C/CAdbcDriverImporter.cs 
b/csharp/src/Apache.Arrow.Adbc/C/CAdbcDriverImporter.cs
index 41f5c48d73..19b85e123a 100644
--- a/csharp/src/Apache.Arrow.Adbc/C/CAdbcDriverImporter.cs
+++ b/csharp/src/Apache.Arrow.Adbc/C/CAdbcDriverImporter.cs
@@ -48,7 +48,8 @@ namespace Apache.Arrow.Adbc.C
         /// Loads an <see cref="AdbcDriver"/> from the file system.
         /// </summary>
         /// <param name="file">The path to the driver to load</param>
-        /// <param name="canUnload">Whether the driver can be safely 
unloaded</param>
+        /// <param name="canUnload">Whether the driver can be safely unloaded. 
A driver compiled with
+        /// NativeAOT can't be, because its runtime's threads keep running 
code in the library.</param>
         /// <param name="entryPoint">The name of the entry point. If not 
provided, the name AdbcDriverInit will be used.</param>
         public static AdbcDriver Load(string file, bool canUnload, string? 
entryPoint = null) =>
             Load(file, canUnload, entryPoint, fallbackEntryPoint: null);
diff --git a/csharp/src/Apache.Arrow.Adbc/C/IdleCollector.cs 
b/csharp/src/Apache.Arrow.Adbc/C/IdleCollector.cs
new file mode 100644
index 0000000000..71ee330685
--- /dev/null
+++ b/csharp/src/Apache.Arrow.Adbc/C/IdleCollector.cs
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace Apache.Arrow.Adbc.C
+{
+    /// <summary>
+    /// Tracks the databases an exported driver has open and runs a collection 
once
+    /// the last one has been released and nothing else has happened for <see 
cref="Delay"/>.
+    /// </summary>
+    internal sealed class IdleCollector
+    {
+        /// <summary>The longest delay that <see cref="Task.Delay(TimeSpan)"/> 
accepts on every runtime.</summary>
+        internal static readonly TimeSpan MaxDelay = 
TimeSpan.FromMilliseconds(int.MaxValue);
+
+        private const long Disabled = -1;
+
+        private readonly Action _collect;
+
+        // The delay in ticks, or Disabled. Stored as a long so that it's read 
atomically.
+        private long _delayTicks;
+        private int _open;
+        private int _generation;
+
+        public IdleCollector(Action collect, TimeSpan? delay)
+        {
+            _collect = collect;
+            Delay = delay;
+        }
+
+        /// <summary>
+        /// How long to wait for the driver to stay idle before collecting, or 
<c>null</c>
+        /// to never collect.
+        /// </summary>
+        public TimeSpan? Delay
+        {
+            get
+            {
+                long ticks = Interlocked.Read(ref _delayTicks);
+                return ticks == Disabled ? null : TimeSpan.FromTicks(ticks);
+            }
+            set
+            {
+                if (value < TimeSpan.Zero || value > MaxDelay)
+                {
+                    throw new ArgumentOutOfRangeException(nameof(value), $"The 
delay must be between zero and {MaxDelay}.");
+                }
+                Interlocked.Exchange(ref _delayTicks, value?.Ticks ?? 
Disabled);
+            }
+        }
+
+        public void DatabaseOpened()
+        {
+            Interlocked.Increment(ref _open);
+            Interlocked.Increment(ref _generation);
+        }
+
+        public void DatabaseReleased()
+        {
+            if (Interlocked.Decrement(ref _open) == 0)
+            {
+                Schedule();
+            }
+        }
+
+        public void DriverReleased()
+        {
+            // Releasing the driver makes more objects unreachable, so it 
starts a new idle
+            // period even if the last database's collection has already run.
+            Interlocked.Increment(ref _generation);
+            if (Volatile.Read(ref _open) == 0)
+            {
+                Schedule();
+            }
+        }
+
+        private void Schedule()
+        {
+            TimeSpan? delay = Delay;
+            if (delay == null)
+            {
+                return;
+            }
+
+            int generation = Volatile.Read(ref _generation);
+            Task.Delay(delay.Value).ContinueWith(_ => 
CollectIfIdle(generation), TaskScheduler.Default);
+        }
+
+        private void CollectIfIdle(int generation)
+        {
+            // Skip if collection was disabled while this was pending, or if 
anything happened
+            // since it was scheduled; the latest release schedules a 
collection of its own.
+            if (Delay == null || Volatile.Read(ref _open) != 0 || 
Volatile.Read(ref _generation) != generation)
+            {
+                return;
+            }
+
+            _collect();
+        }
+    }
+}
diff --git a/csharp/test/Apache.Arrow.Adbc.Tests/IdleCollectorTests.cs 
b/csharp/test/Apache.Arrow.Adbc.Tests/IdleCollectorTests.cs
new file mode 100644
index 0000000000..496fcd5358
--- /dev/null
+++ b/csharp/test/Apache.Arrow.Adbc.Tests/IdleCollectorTests.cs
@@ -0,0 +1,170 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using Apache.Arrow.Adbc.C;
+using Xunit;
+
+namespace Apache.Arrow.Adbc.Tests
+{
+    public class IdleCollectorTests
+    {
+        private static readonly TimeSpan ShortDelay = 
TimeSpan.FromMilliseconds(20);
+
+        // Long enough for a collection scheduled with ShortDelay to have run.
+        private static readonly TimeSpan Settle = 
TimeSpan.FromMilliseconds(500);
+
+        private int _collections;
+
+        private IdleCollector Create(TimeSpan? delay) =>
+            new IdleCollector(() => Interlocked.Increment(ref _collections), 
delay);
+
+        private async Task WaitForCollections(int expected)
+        {
+            DateTime deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
+            while (Volatile.Read(ref _collections) < expected && 
DateTime.UtcNow < deadline)
+            {
+                await Task.Delay(10);
+            }
+            await Task.Delay(Settle);
+            Assert.Equal(expected, Volatile.Read(ref _collections));
+        }
+
+        [Fact]
+        public async Task CollectsAfterLastDatabaseIsReleased()
+        {
+            IdleCollector collector = Create(ShortDelay);
+            collector.DatabaseOpened();
+            collector.DatabaseOpened();
+            collector.DatabaseReleased();
+            await Task.Delay(Settle);
+            Assert.Equal(0, Volatile.Read(ref _collections));
+
+            collector.DatabaseReleased();
+            await WaitForCollections(1);
+        }
+
+        [Fact]
+        public async Task CollectsOnceWhenDriverIsReleasedAfterDatabases()
+        {
+            IdleCollector collector = Create(ShortDelay);
+            collector.DatabaseOpened();
+            collector.DatabaseReleased();
+            collector.DriverReleased();
+            await WaitForCollections(1);
+        }
+
+        [Fact]
+        public async Task 
CollectsAgainWhenDriverIsReleasedAfterDatabaseCollection()
+        {
+            IdleCollector collector = Create(ShortDelay);
+            collector.DatabaseOpened();
+            collector.DatabaseReleased();
+            await WaitForCollections(1);
+
+            collector.DriverReleased();
+            await WaitForCollections(2);
+        }
+
+        [Fact]
+        public async Task CollectsWhenDriverIsReleasedWithoutDatabases()
+        {
+            IdleCollector collector = Create(ShortDelay);
+            collector.DriverReleased();
+            await WaitForCollections(1);
+
+            collector.DriverReleased();
+            await WaitForCollections(2);
+        }
+
+        [Fact]
+        public async Task DisablingCancelsPendingCollection()
+        {
+            IdleCollector collector = Create(TimeSpan.FromMilliseconds(200));
+            collector.DatabaseOpened();
+            collector.DatabaseReleased();
+            collector.Delay = null;
+            await Task.Delay(Settle);
+            Assert.Equal(0, Volatile.Read(ref _collections));
+        }
+
+        [Fact]
+        public async Task SkipsCollectionWhenDatabaseIsReopenedDuringDelay()
+        {
+            IdleCollector collector = Create(TimeSpan.FromMilliseconds(200));
+            collector.DatabaseOpened();
+            collector.DatabaseReleased();
+            collector.DatabaseOpened();
+            await Task.Delay(Settle);
+            Assert.Equal(0, Volatile.Read(ref _collections));
+
+            collector.DatabaseReleased();
+            await WaitForCollections(1);
+        }
+
+        [Fact]
+        public async Task CollectsAgainAfterLaterIdlePeriod()
+        {
+            IdleCollector collector = Create(ShortDelay);
+            collector.DatabaseOpened();
+            collector.DatabaseReleased();
+            await WaitForCollections(1);
+
+            collector.DatabaseOpened();
+            collector.DatabaseReleased();
+            await WaitForCollections(2);
+        }
+
+        [Fact]
+        public async Task NullDelayDisablesCollection()
+        {
+            IdleCollector collector = Create(null);
+            collector.DatabaseOpened();
+            collector.DatabaseReleased();
+            collector.DriverReleased();
+            await Task.Delay(Settle);
+            Assert.Equal(0, Volatile.Read(ref _collections));
+        }
+
+        [Fact]
+        public void OutOfRangeDelayIsRejected()
+        {
+            TimeSpan tooLong = IdleCollector.MaxDelay + 
TimeSpan.FromMilliseconds(1);
+            Assert.Throws<ArgumentOutOfRangeException>(() => 
Create(TimeSpan.FromMilliseconds(-1)));
+            Assert.Throws<ArgumentOutOfRangeException>(() => Create(tooLong));
+            Assert.Throws<ArgumentOutOfRangeException>(() => 
Create(TimeSpan.MaxValue));
+
+            IdleCollector collector = Create(null);
+            Assert.Throws<ArgumentOutOfRangeException>(() => collector.Delay = 
TimeSpan.FromMilliseconds(-1));
+            Assert.Throws<ArgumentOutOfRangeException>(() => collector.Delay = 
tooLong);
+            Assert.Null(collector.Delay);
+
+            collector.Delay = TimeSpan.Zero;
+            Assert.Equal(TimeSpan.Zero, collector.Delay);
+            collector.Delay = IdleCollector.MaxDelay;
+            Assert.Equal(IdleCollector.MaxDelay, collector.Delay);
+        }
+
+        [Fact]
+        public void ExporterDoesNotCollectByDefaultWhenJitCompiled()
+        {
+            Assert.Null(CAdbcDriverExporter.IdleCollectionDelay);
+        }
+    }
+}

Reply via email to