Исправить U+0000 и гонку готовности PostgreSQL; добавить проверки

This commit is contained in:
2026-10-23 12:26:15 +03:00
parent 400e62ffdc
commit 01ecc8567e
20 changed files with 1123 additions and 717 deletions
+10 -5
View File
@@ -43,19 +43,23 @@ def main():
with psycopg.connect(url, autocommit=True) as admin:
admin.execute(sql.SQL('CREATE DATABASE {}').format(sql.Identifier(database)))
conn = psycopg.connect(make_conninfo(url, dbname=database))
conn.execute((ROOT / 'migrations/001_initial.sql').read_text())
for migration in sorted((ROOT / 'migrations').glob('*.sql')):
conn.execute(migration.read_text())
user = uuid.uuid4()
conn.execute('INSERT INTO users (id, username, display_name, password_hash) VALUES (%s, %s, %s, %s)', (user, 'research_user', 'Synthetic', 'not-an-authenticatable-password'))
conn.execute('INSERT INTO users (id, username, display_name, password_hash) VALUES (%s, %s, %s, %s)', (user, 'research_user', b'Synthetic', 'not-an-authenticatable-password'))
sizes = [70000, 20000, 5000, 2000, 1000, 800, 500, 300, 200, 200]
chats = [uuid.uuid4() for _ in sizes]
base = dt.datetime(2026, 1, 1, tzinfo=dt.timezone.utc)
for chat in chats:
conn.execute('INSERT INTO chats (id, title) VALUES (%s, %s)', (chat, 'Synthetic'))
conn.execute('INSERT INTO chats (id, title) VALUES (%s, %s)', (chat, b'Synthetic'))
conn.execute('INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)', (chat, user))
with conn.cursor().copy('COPY messages (id, chat_id, sender_id, text, created_at) FROM STDIN') as copy:
for chat, count in zip(chats, sizes):
for i in range(count):
copy.write_row((uuid.uuid4(), chat, user, 'x' * 64, base + dt.timedelta(microseconds=i)))
first = chat == chats[0] and i == 0
mid = uuid.UUID(int=0) if first else uuid.uuid4()
content = b'A\x00B' + b'x' * 61 if first else b'x' * 64
copy.write_row((mid, chat, user, content, base + dt.timedelta(microseconds=i)))
conn.commit()
results = []
query = '''
@@ -93,7 +97,7 @@ def main():
started = time.perf_counter()
with conn.cursor().copy('COPY messages (id, chat_id, sender_id, text, created_at) FROM STDIN') as copy:
for i, mid in enumerate(ids):
copy.write_row((mid, chats[0], user, 'write-cost', base + dt.timedelta(seconds=1, microseconds=i)))
copy.write_row((mid, chats[0], user, b'write-cost', base + dt.timedelta(seconds=1, microseconds=i)))
conn.commit()
elapsed = (time.perf_counter() - started) * 1000
wal = conn.execute('SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(), %s::pg_lsn)', (before,)).fetchone()[0]
@@ -104,6 +108,7 @@ def main():
results.append(dict(variant=variant, index_bytes=index_size, reads=reads, writes=writes))
captured = snapshot(conn)
assert captured['counts']['messages'] == 100000
assert captured['selected_messages'][0]['text'] == '\\x' + (b'A\x00B' + b'x' * 61).hex()
version = conn.execute('SELECT version()').fetchone()[0]
conn.close()
print(json.dumps(dict(database=database, postgresql=version, sizes=sizes, query=query, repeats=5, results=results, snapshot=captured)))
+4 -2
View File
@@ -34,13 +34,15 @@ started_bootstrap = time.perf_counter()
restore_id = subprocess.check_output(['docker', 'run', '-d', '--name', restore_container, '--network', network, '--cpus=1', '--memory=512m', '-e', 'POSTGRES_USER=messenger', '-e', 'POSTGRES_DB=' + restore, '-e', 'POSTGRES_PASSWORD_FILE=/run/secrets/postgres_password', '--mount', 'type=volume,src=' + restore_volume + ',dst=/var/lib/postgresql/data', '--mount', 'type=bind,src=' + str(ROOT / 'secrets/postgres_password') + ',dst=/run/secrets/postgres_password,readonly', image], text=True).strip()
try:
deadline = time.monotonic() + 45
while subprocess.run(['docker', 'exec', restore_container, 'pg_isready', '-U', 'messenger', '-d', restore], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode:
# The entrypoint's temporary init server accepts Unix sockets only.
# TCP becomes ready only after initialization has finished and it is replaced.
while subprocess.run(['docker', 'exec', restore_container, 'pg_isready', '-h', '127.0.0.1', '-U', 'messenger', '-d', restore], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode:
assert time.monotonic() < deadline, 'new PostgreSQL did not become ready'
time.sleep(0.3)
bootstrap_seconds = time.perf_counter() - started_bootstrap
started = time.perf_counter()
with backup.open('rb') as data:
subprocess.run(['docker', 'exec', '-i', restore_container, 'pg_restore', '-U', 'messenger', '--no-owner', '--exit-on-error', '-d', restore], stdin=data, check=True)
subprocess.run(['docker', 'exec', '-i', restore_container, 'pg_restore', '-h', '127.0.0.1', '-U', 'messenger', '--no-owner', '--exit-on-error', '-d', restore], stdin=data, check=True)
restore_seconds = time.perf_counter() - started
verified = json.loads(subprocess.check_output(RUN + ['-e', 'RESEARCH_DATABASE=' + restore, '-e', 'RESEARCH_HOST=' + restore_container, 'api', 'python', 'student-tests/index_study.py', '--verify'], text=True))
finally:
+22
View File
@@ -29,6 +29,28 @@ class APIContract(unittest.TestCase):
self.assertEqual(result['text'], '👩' * 4000)
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, body={'text': '👩' * 4001})
def test_unicode_nul_round_trip(self):
import base64
value = 'A\x00B\\u0000👩'
registration = dict(self.alice['registration'], username='nul_' + uuid.uuid4().hex[:20], display_name=value)
user = self.client.call('POST', '/api/v1/users', 201, body=registration, schema='User')['json']
self.assertEqual(user['display_name'], value)
credential = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
session = self.client.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
self.assertEqual(session['user'], user)
actor = {'id': user['id'], 'token': session['token']}
# Exercise the database path and then the Redis profile cache.
for _ in range(2):
self.assertEqual(self.client.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json'], user)
chat = self.client.call('POST', '/api/v1/chats', 201, actor=actor, body={'title': value, 'member_ids': [actor['id']]}, schema='Chat')['json']
self.assertEqual(chat['title'], value)
self.assertEqual(self.client.call('GET', '/api/v1/chats/' + chat['id'], actor=actor, schema='Chat')['json'], chat)
contents = [value, '\x00' * 4000, '👩' * 3999 + '\x00']
for content in contents:
self.assertEqual(self.client.message(actor, chat, content)['json']['text'], content)
history = self.client.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=actor, schema='MessagePage')['json']
self.assertEqual([message['text'] for message in history['items']], contents)
def test_foreign_chat(self):
for suffix in ('', '/messages'):
self.client.call('GET', self.path + suffix, 404, actor=self.eve)