Skip to content

Commit

Permalink
Add seconds to engine program id generation (#3906)
Browse files Browse the repository at this point in the history
- Clients were occasionally getting duplicate program ids
when running successive results.
- Root cause is unknown, but likely cause is that a sub-module
was calling random.seed() somewhere.
- This changes program id generation to include seconds in the id,
so that successive calls will generate distinct ids even if the
random number generator is seeded.

Co-authored-by: Cirq Bot <craiggidney+github+cirqbot@google.com>
  • Loading branch information
dstrain115 and CirqBot committed Mar 16, 2021
1 parent 9465afc commit 8cf7825
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
2 changes: 1 addition & 1 deletion cirq/google/engine/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ class ProtoVersion(enum.Enum):
def _make_random_id(prefix: str, length: int = 16):
random_digits = [random.choice(string.ascii_uppercase + string.digits) for _ in range(length)]
suffix = ''.join(random_digits)
suffix += datetime.date.today().strftime('%y%m%d')
suffix += datetime.date.today().strftime('%y%m%d-%H%M%S')
return f'{prefix}{suffix}'


Expand Down
12 changes: 12 additions & 0 deletions cirq/google/engine/engine_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"""Tests for engine."""
import os
from unittest import mock
import time
import numpy as np
import pytest

Expand Down Expand Up @@ -264,6 +265,17 @@ def _to_timestamp(json_string):
)


def test_make_random_id():
with mock.patch('random.choice', return_value='A'):
random_id = cg.engine.engine._make_random_id('prefix-', length=4)
assert random_id[:11] == 'prefix-AAAA'
random_id = cg.engine.engine._make_random_id('prefix-')
time.sleep(1)
random_id2 = cg.engine.engine._make_random_id('prefix-')
# Verify program id generate distinct even if random is seeded
assert random_id != random_id2


@pytest.fixture(scope='session', autouse=True)
def mock_grpc_client():
with mock.patch(
Expand Down

0 comments on commit 8cf7825

Please sign in to comment.