Skip to content

Commit

Permalink
fix: use a fixed hash seed for variant hashing, this fixes a bug in v…
Browse files Browse the repository at this point in the history
…ariant distribution (#179)
  • Loading branch information
sighphyre committed Nov 3, 2023
1 parent 76747af commit f511462
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 5 deletions.
4 changes: 2 additions & 2 deletions src/Stickiness/MurmurHashCalculator.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

final class MurmurHashCalculator implements StickinessCalculator
{
public function calculate(string $id, string $groupId, int $normalizer = 100): int
public function calculate(string $id, string $groupId, int $normalizer = 100, int $seed = 0): int
{
return Murmur::hash3_int("{$groupId}:{$id}") % $normalizer + 1;
return Murmur::hash3_int("{$groupId}:{$id}", $seed) % $normalizer + 1;
}
}
2 changes: 1 addition & 1 deletion src/Stickiness/StickinessCalculator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@

interface StickinessCalculator
{
public function calculate(string $id, string $groupId, int $normalizer = 100): int;
public function calculate(string $id, string $groupId, int $normalizer = 100, int $seed = 0): int;
}
4 changes: 3 additions & 1 deletion src/Variant/DefaultVariantHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

final readonly class DefaultVariantHandler implements VariantHandler
{
private const VARIANT_HASH_SEED = 86028157;

public function __construct(
private StickinessCalculator $stickinessCalculator,
) {
Expand Down Expand Up @@ -103,7 +105,7 @@ private function calculateStickiness(
?? $this->randomString();
}

return $this->stickinessCalculator->calculate($seed, $groupId, $totalWeight);
return $this->stickinessCalculator->calculate($seed, $groupId, $totalWeight, $seed = DefaultVariantHandler::VARIANT_HASH_SEED);
}

private function randomString(): string
Expand Down

0 comments on commit f511462

Please sign in to comment.