-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathtest_engine.py
More file actions
635 lines (570 loc) · 24 KB
/
test_engine.py
File metadata and controls
635 lines (570 loc) · 24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import os
import uuid
from typing import Any, Coroutine, Sequence
import asyncpg # type: ignore
import pytest
import pytest_asyncio
from google.cloud.sql.connector import Connector, IPTypes
from langchain_core.embeddings import DeterministicFakeEmbedding
from sqlalchemy import VARCHAR, text
from sqlalchemy.engine import URL
from sqlalchemy.engine.row import RowMapping
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.pool import NullPool
from langchain_google_cloud_sql_pg import Column, HybridSearchConfig, PostgresEngine
DEFAULT_TABLE = "test_table" + str(uuid.uuid4()).replace("-", "_")
CUSTOM_TABLE = "test_table_custom" + str(uuid.uuid4()).replace("-", "_")
INT_ID_CUSTOM_TABLE = "test_table_custom_int_id" + str(uuid.uuid4()).replace("-", "_")
HYBRID_SEARCH_TABLE = "hybrid" + str(uuid.uuid4()).replace("-", "_")
DEFAULT_TABLE_SYNC = "test_table" + str(uuid.uuid4()).replace("-", "_")
CUSTOM_TABLE_SYNC = "test_table_custom" + str(uuid.uuid4()).replace("-", "_")
INT_ID_CUSTOM_TABLE_SYNC = "test_table_custom_int_id" + str(uuid.uuid4()).replace(
"-", "_"
)
HYBRID_SEARCH_TABLE_SYNC = "hybrid_sync" + str(uuid.uuid4()).replace("-", "_")
VECTOR_SIZE = 768
embeddings_service = DeterministicFakeEmbedding(size=VECTOR_SIZE)
host = os.environ["IP_ADDRESS"]
def get_env_var(key: str, desc: str) -> str:
v = os.environ.get(key)
if v is None:
raise ValueError(f"Must set env var {key} to: {desc}")
return v
# Helper to bridge the Main Test Loop and the Engine Background Loop
async def run_on_background(engine: PostgresEngine, coro: Coroutine) -> Any:
"""Runs a coroutine on the engine's background loop (if it exists)."""
if engine._loop:
return await asyncio.wrap_future(
asyncio.run_coroutine_threadsafe(coro, engine._loop)
)
return await coro
async def aexecute(
engine: PostgresEngine,
query: str,
) -> None:
async def _impl():
async with engine._pool.connect() as conn:
await conn.execute(text(query))
await conn.commit()
await run_on_background(engine, _impl())
async def afetch(engine: PostgresEngine, query: str) -> Sequence[RowMapping]:
async def _impl():
async with engine._pool.connect() as conn:
result = await conn.execute(text(query))
result_map = result.mappings()
return result_map.fetchall()
return await run_on_background(engine, _impl())
@pytest.mark.asyncio(scope="module")
class TestEngineAsync:
@pytest.fixture(scope="module")
def db_project(self) -> str:
return get_env_var("PROJECT_ID", "project id for google cloud")
@pytest.fixture(scope="module")
def db_region(self) -> str:
return get_env_var("REGION", "region for cloud sql instance")
@pytest.fixture(scope="module")
def db_instance(self) -> str:
return get_env_var("INSTANCE_ID", "instance for cloud sql")
@pytest.fixture(scope="module")
def db_name(self) -> str:
return get_env_var("DATABASE_ID", "instance for cloud sql")
@pytest.fixture(scope="module")
def user(self) -> str:
return get_env_var("DB_USER", "database user for cloud sql")
@pytest.fixture(scope="module")
def password(self) -> str:
return get_env_var("DB_PASSWORD", "database password for cloud sql")
@pytest.fixture(scope="module")
def iam_account(self) -> str:
return get_env_var("IAM_ACCOUNT", "Cloud SQL IAM account email")
@pytest_asyncio.fixture(scope="class")
async def engine(self, db_project, db_region, db_instance, db_name):
engine = await PostgresEngine.afrom_instance(
project_id=db_project,
instance=db_instance,
region=db_region,
database=db_name,
engine_args={
# add some connection args to validate engine_args works correctly
"pool_size": 3,
"max_overflow": 2,
},
)
yield engine
await aexecute(engine, f'DROP TABLE "{CUSTOM_TABLE}"')
await aexecute(engine, f'DROP TABLE "{DEFAULT_TABLE}"')
await aexecute(engine, f'DROP TABLE "{INT_ID_CUSTOM_TABLE}"')
await aexecute(engine, f'DROP TABLE "{HYBRID_SEARCH_TABLE}"')
await engine.close()
async def test_engine_args(self, engine):
# Accessing engine._pool.pool.status() is synchronous and safe on main loop objects
# assuming SQLAlchemy pool status doesn't strictly require loop context
assert "Pool size: 3" in engine._pool.pool.status()
async def test_init_table(self, engine):
await run_on_background(
engine, engine.ainit_vectorstore_table(DEFAULT_TABLE, VECTOR_SIZE)
)
id = str(uuid.uuid4())
content = "coffee"
embedding = await embeddings_service.aembed_query(content)
# Note: DeterministicFakeEmbedding generates a numpy array, converting to list a list of float values
embedding_string = [float(dimension) for dimension in embedding]
stmt = f"INSERT INTO {DEFAULT_TABLE} (langchain_id, content, embedding) VALUES ('{id}', '{content}','{embedding_string}');"
await aexecute(engine, stmt)
async def test_init_table_custom(self, engine):
await run_on_background(
engine,
engine.ainit_vectorstore_table(
CUSTOM_TABLE,
VECTOR_SIZE,
id_column="uuid",
content_column="my-content",
embedding_column="my_embedding",
metadata_columns=[Column("page", "TEXT"), Column("source", "TEXT")],
store_metadata=True,
),
)
stmt = f"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '{CUSTOM_TABLE}';"
results = await afetch(engine, stmt)
expected = [
{"column_name": "uuid", "data_type": "uuid"},
{"column_name": "my_embedding", "data_type": "USER-DEFINED"},
{"column_name": "langchain_metadata", "data_type": "json"},
{"column_name": "my-content", "data_type": "text"},
{"column_name": "page", "data_type": "text"},
{"column_name": "source", "data_type": "text"},
]
for row in results:
assert row in expected
async def test_init_table_with_int_id(self, engine):
await run_on_background(
engine,
engine.ainit_vectorstore_table(
INT_ID_CUSTOM_TABLE,
VECTOR_SIZE,
id_column=Column(
name="integer_id", data_type="INTEGER", nullable="False"
),
content_column="my-content",
embedding_column="my_embedding",
metadata_columns=[Column("page", "TEXT"), Column("source", "TEXT")],
store_metadata=True,
),
)
stmt = f"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '{INT_ID_CUSTOM_TABLE}';"
results = await afetch(engine, stmt)
expected = [
{"column_name": "integer_id", "data_type": "integer"},
{"column_name": "my_embedding", "data_type": "USER-DEFINED"},
{"column_name": "langchain_metadata", "data_type": "json"},
{"column_name": "my-content", "data_type": "text"},
{"column_name": "page", "data_type": "text"},
{"column_name": "source", "data_type": "text"},
]
for row in results:
assert row in expected
async def test_password(
self,
db_project,
db_region,
db_instance,
db_name,
user,
password,
):
# Note: PostgresEngine._connector is no longer a class attribute in fixed engine.py
# But for test cleanup safety regarding the OLD code structure, we can ignore this.
# PostgresEngine._connector = None
engine = await PostgresEngine.afrom_instance(
project_id=db_project,
instance=db_instance,
region=db_region,
database=db_name,
user=user,
password=password,
)
assert engine
await aexecute(engine, "SELECT 1")
await engine.close()
async def test_from_engine(
self,
db_project,
db_region,
db_instance,
db_name,
user,
password,
):
async with Connector(loop=asyncio.get_running_loop()) as connector:
async def getconn() -> asyncpg.Connection:
conn = await connector.connect_async( # type: ignore
f"{db_project}:{db_region}:{db_instance}",
"asyncpg",
user=user,
password=password,
db=db_name,
enable_iam_auth=False,
ip_type=IPTypes.PUBLIC,
)
return conn
engine_async = create_async_engine(
"postgresql+asyncpg://",
async_creator=getconn,
)
engine = PostgresEngine.from_engine(engine_async)
await aexecute(engine, "SELECT 1")
await engine.close()
async def test_from_connection_string(
self,
db_name,
user,
password,
):
port = "5432"
url = f"postgresql+asyncpg://{user}:{password}@{host}:{port}/{db_name}"
engine = PostgresEngine.from_connection_string(
url,
echo=True,
poolclass=NullPool,
)
await aexecute(engine, "SELECT 1")
await engine.close()
engine = PostgresEngine.from_connection_string(
URL.create("postgresql+asyncpg", user, password, host, port, db_name)
)
await aexecute(engine, "SELECT 1")
await engine.close()
async def test_from_engine_args_url(
self,
db_name,
user,
password,
):
port = "5432"
url = f"postgresql+asyncpg://{user}:{password}@{host}:{port}/{db_name}"
engine = PostgresEngine.from_engine_args(
url,
echo=True,
poolclass=NullPool,
)
await aexecute(engine, "SELECT 1")
await engine.close()
engine = PostgresEngine.from_engine_args(
URL.create("postgresql+asyncpg", user, password, host, port, db_name)
)
await aexecute(engine, "SELECT 1")
await engine.close()
async def test_from_engine_args_url_error(
self,
db_name,
user,
password,
):
port = "5432"
url = f"postgresql+asyncpg://{user}:{password}@{host}:{port}/{db_name}"
with pytest.raises(TypeError):
engine = PostgresEngine.from_engine_args(url, random=False)
with pytest.raises(ValueError):
PostgresEngine.from_engine_args(
f"postgresql+pg8000://{user}:{password}@{host}:{port}/{db_name}",
)
with pytest.raises(ValueError):
PostgresEngine.from_engine_args(
URL.create("postgresql+pg8000", user, password, host, port, db_name)
)
async def test_column(self, engine):
with pytest.raises(ValueError):
Column("test", VARCHAR)
with pytest.raises(ValueError):
Column(1, "INTEGER")
async def test_iam_account_override(
self,
db_project,
db_instance,
db_region,
db_name,
iam_account,
engine,
):
engine = await PostgresEngine.afrom_instance(
project_id=db_project,
instance=db_instance,
region=db_region,
database=db_name,
iam_account_email=iam_account,
)
assert engine
await aexecute(engine, "SELECT 1")
await engine.close()
async def test_ainit_checkpoint_writes_table(self, engine):
table_name = f"checkpoint{uuid.uuid4()}"
table_name_writes = f"{table_name}_writes"
await run_on_background(
engine, engine.ainit_checkpoint_table(table_name=table_name)
)
stmt = f"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '{table_name_writes}';"
results = await afetch(engine, stmt)
expected = [
{"column_name": "thread_id", "data_type": "text"},
{"column_name": "checkpoint_ns", "data_type": "text"},
{"column_name": "checkpoint_id", "data_type": "text"},
{"column_name": "task_id", "data_type": "text"},
{"column_name": "idx", "data_type": "integer"},
{"column_name": "channel", "data_type": "text"},
{"column_name": "type", "data_type": "text"},
{"column_name": "blob", "data_type": "bytea"},
{"column_name": "task_path", "data_type": "text"},
]
for row in results:
assert row in expected
stmt = f"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '{table_name}';"
results = await afetch(engine, stmt)
expected = [
{"column_name": "thread_id", "data_type": "text"},
{"column_name": "checkpoint_ns", "data_type": "text"},
{"column_name": "checkpoint_id", "data_type": "text"},
{"column_name": "parent_checkpoint_id", "data_type": "text"},
{"column_name": "type", "data_type": "text"},
{"column_name": "checkpoint", "data_type": "bytea"},
{"column_name": "metadata", "data_type": "bytea"},
]
for row in results:
assert row in expected
await aexecute(engine, f'DROP TABLE IF EXISTS "{table_name}"')
await aexecute(engine, f'DROP TABLE IF EXISTS "{table_name_writes}"')
async def test_init_table_hybrid_search(self, engine):
await run_on_background(
engine,
engine.ainit_vectorstore_table(
HYBRID_SEARCH_TABLE,
VECTOR_SIZE,
id_column="uuid",
content_column="my-content",
embedding_column="my_embedding",
metadata_columns=[Column("page", "TEXT"), Column("source", "TEXT")],
store_metadata=True,
hybrid_search_config=HybridSearchConfig(),
),
)
stmt = f"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '{HYBRID_SEARCH_TABLE}';"
results = await afetch(engine, stmt)
expected = [
{"column_name": "uuid", "data_type": "uuid"},
{"column_name": "my_embedding", "data_type": "USER-DEFINED"},
{"column_name": "langchain_metadata", "data_type": "json"},
{"column_name": "my-content", "data_type": "text"},
{"column_name": "my-content_tsv", "data_type": "tsvector"},
{"column_name": "page", "data_type": "text"},
{"column_name": "source", "data_type": "text"},
]
for row in results:
assert row in expected
@pytest.mark.asyncio(scope="module")
class TestEngineSync:
@pytest.fixture(scope="module")
def db_project(self) -> str:
return get_env_var("PROJECT_ID", "project id for google cloud")
@pytest.fixture(scope="module")
def db_region(self) -> str:
return get_env_var("REGION", "region for cloud sql instance")
@pytest.fixture(scope="module")
def db_instance(self) -> str:
return get_env_var("INSTANCE_ID", "instance for cloud sql")
@pytest.fixture(scope="module")
def db_name(self) -> str:
return get_env_var("DATABASE_ID", "instance for cloud sql")
@pytest.fixture(scope="module")
def user(self) -> str:
return get_env_var("DB_USER", "database user for cloud sql")
@pytest.fixture(scope="module")
def password(self) -> str:
return get_env_var("DB_PASSWORD", "database password for cloud sql")
@pytest.fixture(scope="module")
def iam_account(self) -> str:
return get_env_var("IAM_ACCOUNT", "Cloud SQL IAM account email")
@pytest_asyncio.fixture(scope="class")
async def engine(self, db_project, db_region, db_instance, db_name):
engine = PostgresEngine.from_instance(
project_id=db_project,
instance=db_instance,
region=db_region,
database=db_name,
)
yield engine
await aexecute(engine, f'DROP TABLE "{CUSTOM_TABLE_SYNC}"')
await aexecute(engine, f'DROP TABLE "{DEFAULT_TABLE_SYNC}"')
await aexecute(engine, f'DROP TABLE "{INT_ID_CUSTOM_TABLE_SYNC}"')
await aexecute(engine, f'DROP TABLE "{HYBRID_SEARCH_TABLE_SYNC}"')
await engine.close()
async def test_init_table(self, engine):
# Sync method uses _run_as_sync internally -> safe to call on Main Loop
engine.init_vectorstore_table(DEFAULT_TABLE_SYNC, VECTOR_SIZE)
id = str(uuid.uuid4())
content = "coffee"
embedding = await embeddings_service.aembed_query(content)
embedding_string = [float(dimension) for dimension in embedding]
stmt = f"INSERT INTO {DEFAULT_TABLE_SYNC} (langchain_id, content, embedding) VALUES ('{id}', '{content}','{embedding_string}');"
await aexecute(engine, stmt)
async def test_init_table_custom(self, engine):
engine.init_vectorstore_table(
CUSTOM_TABLE_SYNC,
VECTOR_SIZE,
id_column="uuid",
content_column="my-content",
embedding_column="my_embedding",
metadata_columns=[Column("page", "TEXT"), Column("source", "TEXT")],
store_metadata=True,
)
stmt = f"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '{CUSTOM_TABLE_SYNC}';"
results = await afetch(engine, stmt)
expected = [
{"column_name": "uuid", "data_type": "uuid"},
{"column_name": "my_embedding", "data_type": "USER-DEFINED"},
{"column_name": "langchain_metadata", "data_type": "json"},
{"column_name": "my-content", "data_type": "text"},
{"column_name": "page", "data_type": "text"},
{"column_name": "source", "data_type": "text"},
]
for row in results:
assert row in expected
async def test_init_table_with_int_id(self, engine):
engine.init_vectorstore_table(
INT_ID_CUSTOM_TABLE_SYNC,
VECTOR_SIZE,
id_column=Column(name="integer_id", data_type="INTEGER", nullable=False),
content_column="my-content",
embedding_column="my_embedding",
metadata_columns=[Column("page", "TEXT"), Column("source", "TEXT")],
store_metadata=True,
)
stmt = f"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '{INT_ID_CUSTOM_TABLE_SYNC}';"
results = await afetch(engine, stmt)
expected = [
{"column_name": "integer_id", "data_type": "integer"},
{"column_name": "my_embedding", "data_type": "USER-DEFINED"},
{"column_name": "langchain_metadata", "data_type": "json"},
{"column_name": "my-content", "data_type": "text"},
{"column_name": "page", "data_type": "text"},
{"column_name": "source", "data_type": "text"},
]
for row in results:
assert row in expected
async def test_password(
self,
db_project,
db_region,
db_instance,
db_name,
user,
password,
):
engine = PostgresEngine.from_instance(
project_id=db_project,
instance=db_instance,
region=db_region,
database=db_name,
user=user,
password=password,
quota_project=db_project,
)
assert engine
await aexecute(engine, "SELECT 1")
await engine.close()
async def test_engine_constructor_key(
self,
engine,
):
key = object()
with pytest.raises(Exception):
PostgresEngine(key, engine, None, None)
async def test_iam_account_override(
self,
db_project,
db_instance,
db_region,
db_name,
iam_account,
engine,
):
engine = PostgresEngine.from_instance(
project_id=db_project,
instance=db_instance,
region=db_region,
database=db_name,
iam_account_email=iam_account,
)
assert engine
await aexecute(engine, "SELECT 1")
await engine.close()
async def test_init_checkpoints_table(self, engine):
table_name = f"checkpoint{uuid.uuid4()}"
table_name_writes = f"{table_name}_writes"
engine.init_checkpoint_table(table_name=table_name)
stmt = f"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '{table_name}';"
results = await afetch(engine, stmt)
expected = [
{"column_name": "thread_id", "data_type": "text"},
{"column_name": "checkpoint_ns", "data_type": "text"},
{"column_name": "checkpoint_id", "data_type": "text"},
{"column_name": "parent_checkpoint_id", "data_type": "text"},
{"column_name": "type", "data_type": "text"},
{"column_name": "checkpoint", "data_type": "bytea"},
{"column_name": "metadata", "data_type": "bytea"},
]
for row in results:
assert row in expected
stmt = f"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '{table_name_writes}';"
results = await afetch(engine, stmt)
expected = [
{"column_name": "thread_id", "data_type": "text"},
{"column_name": "checkpoint_ns", "data_type": "text"},
{"column_name": "checkpoint_id", "data_type": "text"},
{"column_name": "task_id", "data_type": "text"},
{"column_name": "idx", "data_type": "integer"},
{"column_name": "channel", "data_type": "text"},
{"column_name": "type", "data_type": "text"},
{"column_name": "blob", "data_type": "bytea"},
{"column_name": "task_path", "data_type": "text"},
]
for row in results:
assert row in expected
await aexecute(engine, f'DROP TABLE IF EXISTS "{table_name}"')
await aexecute(engine, f'DROP TABLE IF EXISTS "{table_name_writes}"')
async def test_init_table_hybrid_search(self, engine):
engine.init_vectorstore_table(
HYBRID_SEARCH_TABLE_SYNC,
VECTOR_SIZE,
id_column="uuid",
content_column="my-content",
embedding_column="my_embedding",
metadata_columns=[Column("page", "TEXT"), Column("source", "TEXT")],
store_metadata=True,
hybrid_search_config=HybridSearchConfig(),
)
stmt = f"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '{HYBRID_SEARCH_TABLE_SYNC}';"
results = await afetch(engine, stmt)
expected = [
{"column_name": "uuid", "data_type": "uuid"},
{"column_name": "my_embedding", "data_type": "USER-DEFINED"},
{"column_name": "langchain_metadata", "data_type": "json"},
{"column_name": "my-content", "data_type": "text"},
{"column_name": "my-content_tsv", "data_type": "tsvector"},
{"column_name": "page", "data_type": "text"},
{"column_name": "source", "data_type": "text"},
]
for row in results:
assert row in expected