Skip to content

Commit

Permalink
fix: use a known hash seed for variant hashing, this fixes a bug in v…
Browse files Browse the repository at this point in the history
…ariant distribution
  • Loading branch information
sighphyre committed Oct 30, 2023
1 parent d60019b commit 270cf42
Show file tree
Hide file tree
Showing 3 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;
}
6 changes: 4 additions & 2 deletions src/Variant/DefaultVariantHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

final class DefaultVariantHandler implements VariantHandler
{
const VARIANT_HASH_SEED = 86028157;

public function __construct(
private readonly StickinessCalculator $stickinessCalculator,
) {
Expand Down Expand Up @@ -94,7 +96,7 @@ private function calculateStickiness(
int $totalWeight
): int {
$stickiness = $variants[0]->getStickiness();
if ($stickiness !== Stickiness::DEFAULT) {
if ($stickiness !== Stickiness::DEFAULT ) {
$seed = $context->findContextValue($stickiness) ?? $this->randomString();
} else {
$seed = $context->getCurrentUserId()
Expand All @@ -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 270cf42

Please sign in to comment.