{"record":{"id":"6ccabdec32c887e5","repo":"LykosAI/StabilityMatrix","slug":"json-does-not-start-with","errorCode":null,"errorMessage":"JSON does not start with '{'.","messagePattern":"JSON does not start with '\\{'\\.","errorType":"validation","errorClass":"InvalidDataException","httpStatus":null,"severity":"error","filePath":"StabilityMatrix.Core/Models/SafetensorMetadata.cs","lineNumber":48,"sourceCode":"    /// <param name=\"safetensorStream\">Stream to the SafeTensor file.</param>\n    /// <returns>The parsed metadata. Can be <see langword=\"null\"/> if the file does not contain metadata.</returns>\n    public static async Task<SafetensorMetadata?> ParseAsync(Stream safetensorStream)\n    {\n        // 8 bytes unsigned little-endian 64-bit integer\n        // 1 byte start of JSON object '{'\n        Memory<byte> buffer = new byte[9];\n        await safetensorStream.ReadExactlyAsync(buffer).ConfigureAwait(false);\n        var span = buffer.Span;\n\n        const ulong MAX_ALLOWED_JSON_LENGTH = 100 * 1024 * 1024; // 100 MB\n        var jsonLength = BinaryPrimitives.ReadUInt64LittleEndian(span);\n        if (jsonLength > MAX_ALLOWED_JSON_LENGTH)\n        {\n            throw new InvalidDataException(\"JSON length exceeds the maximum allowed size.\");\n        }\n        if (span[8] != '{')\n        {\n            throw new InvalidDataException(\"JSON does not start with '{'.\");\n        }\n\n        // Unfornately Utf8JsonReader does not support reading from a stream directly.\n        // Usually the size of the entire JSON object is less than 500KB,\n        // using a pooled buffer should reduce the number of large allocations.\n        var jsonBytes = ArrayPool<byte>.Shared.Rent((int)jsonLength);\n        try\n        {\n            // Important: the length of the rented buffer can be larger than jsonLength\n            // and there can be additional junk data at the end.\n\n            // we already read {, so start from index 1\n            jsonBytes[0] = (byte)'{';\n            await safetensorStream\n                .ReadExactlyAsync(jsonBytes, 1, (int)(jsonLength - 1))\n                .ConfigureAwait(false);\n\n            // read the JSON with Utf8JsonReader, then only deserialize what we need","sourceCodeStart":30,"sourceCodeEnd":66,"githubUrl":"https://github.com/LykosAI/StabilityMatrix/blob/af93d6ef57c01cd890d7e0ad0a9ea8c9fcda3002/StabilityMatrix.Core/Models/SafetensorMetadata.cs#L30-L66","documentation":"ParseAsync throws this when byte 8 of the safetensors file (the first byte of the JSON header) is not '{'. The 8-byte length prefix must be immediately followed by the opening brace of the JSON header.","triggerScenarios":"Reading a file whose byte at offset 8 is not '{': non-safetensors files, wrong stream position, headers whose length prefix is misinterpreted.","commonSituations":"Renamed model files (ckpt/gguf named .safetensors), partially written files, reading from a stream that was already partially consumed.","solutions":["Verify the file is a genuine safetensors file (magic: 8-byte little-endian length then '{').","Reset the stream position to 0 before calling ParseAsync.","Re-download or re-convert the model file.","Add a pre-check that reads the first 9 bytes and validates the pattern."],"exampleFix":"// before\nvar meta = await SafetensorMetadata.ParseAsync(fileStream);\n// after\nfileStream.Position = 0;\nvar probe = new byte[9];\nawait fileStream.ReadExactlyAsync(probe);\nif (probe[8] != (byte)'{') throw new InvalidDataException(\"Not a safetensors file.\");\nfileStream.Position = 0;\nvar meta = await SafetensorMetadata.ParseAsync(fileStream);","handlingStrategy":"validation","validationCode":"using var fs = File.OpenRead(path);\nvar probe = new byte[9];\nif (await fs.ReadAsync(probe) < 9 || probe[8] != (byte)'{')\n    throw new InvalidDataException(\"File does not look like safetensors.\");\nfs.Position = 0;","typeGuard":"bool LooksLikeSafetensors(byte[] first9) => first9.Length >= 9 && first9[8] == (byte)'{';","tryCatchPattern":"try { var meta = await SafetensorMetadata.ParseAsync(stream); }\ncatch (InvalidDataException ex)\n{\n    _logger.LogError(ex, \"Not a valid safetensors file\");\n    notificationService.ShowPersistentDialog(\"Invalid file\", ex.Message);\n}","preventionTips":["Validate file magic/header before parsing","Re-download files that fail validation instead of retrying parses","Ensure the stream was not already partially consumed","Check downloads complete before hashing/parsing"],"tags":["safetensors","file-format","validation"],"backgroundTag":"invalid-json-response","analyzedSha":"af93d6ef57c01cd890d7e0ad0a9ea8c9fcda3002","analyzedAt":"2026-09-12T19:02:43.389Z","contentChangedAt":"2026-09-12T19:02:43.389Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}