Skip to content

fix: add sort before hashing attributes #51

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions src/attributes.zig
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,29 @@ pub const Attributes = struct {
}

pub const HashContext = struct {
pub fn hash(_: HashContext, self: Self) u64 {
fn compareAttributes(context: void, a: Attribute, b: Attribute) bool {
_ = context;
return std.mem.lessThan(u8, a.key, b.key);
}

const MAX_ATTRS = 128;

pub fn hash(_: HashContext, self: Attributes) u64 {
var h = std.hash.Wyhash.init(0);
const attrs = self.attributes orelse &[_]Attribute{};
for (attrs) |attr| {

// Enforce soft limit: only hash up to MAX_ATTRS attributes
const count = @min(attrs.len, MAX_ATTRS);

var buffer: [MAX_ATTRS]Attribute = undefined;
const to_sort = buffer[0..count];
@memcpy(to_sort, attrs[0..count]);

if (to_sort.len > 1) {
std.mem.sort(Attribute, to_sort, {}, compareAttributes);
}

for (to_sort) |attr| {
h.update(attr.key);
h.update(attr.value.toStringNoAlloc());
}
Expand Down
18 changes: 18 additions & 0 deletions src/scope.zig
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,21 @@ test "InstrumentationScope should equal correctly" {

try std.testing.expect(hashContext.eql(first, second));
}

test "InstrumentationScope hash should be consistent regardless of attribute order" {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for adding the test 🙏🏼

const allocator = std.testing.allocator;

const attrs1 = try Attributes.from(allocator, .{ "key1", @as(u64, 42), "key2", true, "key3", @as([]const u8, "value3") });
defer allocator.free(attrs1.?);

const attrs2 = try Attributes.from(allocator, .{ "key3", @as([]const u8, "value3"), "key1", @as(u64, 42), "key2", true });
defer allocator.free(attrs2.?);

const scope1: InstrumentationScope = .{ .name = "testScope", .attributes = attrs1 };
const scope2: InstrumentationScope = .{ .name = "testScope", .attributes = attrs2 };

const hashContext = InstrumentationScope.HashContext{};

try std.testing.expectEqual(hashContext.hash(scope1), hashContext.hash(scope2));
try std.testing.expect(hashContext.eql(scope1, scope2));
}