{"record":{"id":"504166d9121a693f","repo":"microsoft/garnet","slug":"failed-to-create-bftree-instance","errorCode":null,"errorMessage":"Failed to create BfTree instance.","messagePattern":"Failed to create BfTree instance\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"critical","filePath":"libs/native/bftree-garnet/BfTreeService.cs","lineNumber":172,"sourceCode":"            uint cbMaxRecordSize = 0,\n            uint cbMaxKeyLen = 0,\n            uint leafPageSize = 0)\n        {\n            _storageBackend = storageBackend;\n            _filePath = filePath;\n            if (storageBackend == StorageBackendType.Disk && string.IsNullOrEmpty(filePath))\n                throw new ArgumentException(\"filePath is required for disk-backed trees.\", nameof(filePath));\n            byte[] pathBytes = filePath != null ? Encoding.UTF8.GetBytes(filePath) : null;\n            byte useSnapshot = (byte)(enableSnapshots ? 1 : 0);\n            fixed (byte* pp = pathBytes)\n            {\n                _tree = NativeBfTreeMethods.bftree_create(\n                    cbSizeByte, cbMinRecordSize, cbMaxRecordSize, cbMaxKeyLen, leafPageSize,\n                    (byte)storageBackend, pp, pathBytes?.Length ?? 0,\n                    useSnapshot);\n            }\n            if (_tree == 0)\n                throw new InvalidOperationException(\"Failed to create BfTree instance.\");\n        }\n\n        /// <summary>\n        /// Creates a BfTreeService wrapping an existing native tree pointer (e.g. from snapshot restore).\n        /// Takes ownership of the pointer.\n        /// </summary>\n        internal BfTreeService(nint treePtr, StorageBackendType storageBackend, string filePath = null)\n        {\n            if (treePtr == 0)\n                throw new ArgumentException(\"Tree pointer must not be null.\", nameof(treePtr));\n            _tree = treePtr;\n            _storageBackend = storageBackend;\n            _filePath = filePath;\n        }\n\n        // ---------------------------------------------------------------\n        // Point operations — PinnedSpanByte (zero-overhead for Garnet hot paths)\n        // ---------------------------------------------------------------","sourceCodeStart":154,"sourceCodeEnd":190,"githubUrl":"https://github.com/microsoft/garnet/blob/951b0fc6838721f89d102c2bbe1b914e8d39d700/libs/native/bftree-garnet/BfTreeService.cs#L154-L190","documentation":"Thrown by the BfTreeService constructor when the native bftree_create function returns a null pointer (0). This means the native BfTree library failed to allocate or initialize the tree structure. Possible causes include out-of-memory conditions, invalid parameters (e.g., zero page sizes, impossible record size constraints), file I/O errors when opening the disk path, or missing native library dependencies.","triggerScenarios":"Calling the BfTreeService constructor where the native bftree_create P/Invoke returns 0. This can happen with invalid sizing parameters, insufficient memory, file permission issues on the disk path, or a corrupted/missing native library.","commonSituations":"Running in memory-constrained containers; providing invalid size parameters (cbSizeByte=0 with unreasonable min/max record sizes); file path pointing to a directory that doesn't exist or lacks write permissions; native library not loaded or incompatible architecture.","solutions":["Verify the filePath directory exists and is writable (for disk backend).","Check that cbSizeByte, cbMinRecordSize, cbMaxRecordSize, and leafPageSize are valid non-zero values.","Ensure sufficient memory is available in the container/host environment.","Verify the native BfTree library is loaded and matches the process architecture (x64/x86).","Check native library logs or stderr for additional error detail from bftree_create."],"exampleFix":"// before: zero size params and nonexistent path\nvar svc = new BfTreeService(\n    storageBackend: StorageBackendType.Disk,\n    filePath: \"/nonexistent/path/tree.dat\",\n    cbSizeByte: 0,\n    leafPageSize: 0\n);\n\n// after: valid params and existing directory\nDirectory.CreateDirectory(\"/var/lib/garnet\");\nvar svc = new BfTreeService(\n    storageBackend: StorageBackendType.Disk,\n    filePath: \"/var/lib/garnet/tree.dat\",\n    cbSizeByte: 1024 * 1024 * 100,\n    leafPageSize: 4096\n);","handlingStrategy":"try-catch","validationCode":"// Validate parameters before construction\nif (storageBackend == StorageBackendType.Disk)\n{\n    var dir = Path.GetDirectoryName(filePath);\n    if (!Directory.Exists(dir))\n        throw new DirectoryNotFoundException($\"BfTree directory does not exist: {dir}\");\n}\nif (cbSizeByte == 0) throw new ArgumentException(\"cbSizeByte must be non-zero.\", nameof(cbSizeByte));\nif (leafPageSize == 0) throw new ArgumentException(\"leafPageSize must be non-zero.\", nameof(leafPageSize));","typeGuard":null,"tryCatchPattern":"try\n{\n    var svc = new BfTreeService(storageBackend, filePath, enableSnapshots, cbSizeByte,\n        cbMinRecordSize, cbMaxRecordSize, cbMaxKeyLen, leafPageSize);\n}\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"Failed to create BfTree\"))\n{\n    logger.LogError(ex, \"Native BfTree creation failed. Check memory, path permissions, and parameters.\");\n    throw;\n}","preventionTips":["Verify the file path directory exists and is writable before creating a disk-backed tree.","Provide non-zero, reasonable values for cbSizeByte and leafPageSize.","Ensure the native BfTree library matches the process architecture.","Monitor available memory in containers to avoid allocation failures."],"tags":["bftree","native-interop","initialization","resource-allocation"],"backgroundTag":null,"analyzedSha":"951b0fc6838721f89d102c2bbe1b914e8d39d700","analyzedAt":"2026-08-13T19:01:32.939Z","schemaVersion":2},"datasetVersion":"2026-08-13T19:17:28.613Z"}