-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdataset.py
More file actions
2429 lines (2136 loc) · 96.4 KB
/
dataset.py
File metadata and controls
2429 lines (2136 loc) · 96.4 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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import logging
import os.path
import uuid
import zipfile
from collections import Counter, defaultdict
from collections.abc import Generator, Iterable
from typing import Any, NamedTuple
import yaml
from fastapi import BackgroundTasks, HTTPException, status
from pydantic import ValidationError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from sqlalchemy.sql.expression import func, select, text, update
import statgpt.common.models as models
import statgpt.common.schemas as schemas
from statgpt.admin.audit.decorators import audit_action
from statgpt.admin.auth.auth_context import SystemUserAuthContext
from statgpt.admin.settings.exim import ExImSettings, JobsConfig
from statgpt.common import utils
from statgpt.common.auth.auth_context import AuthContext
from statgpt.common.data import base
from statgpt.common.data.base.dataset import DataSetConfigType
from statgpt.common.hybrid_indexer import Indexer
from statgpt.common.schemas import (
AuditActionType,
AuditEntityType,
AutoUpdateResult,
ChannelIndexStatusScope,
HybridSearchConfig,
)
from statgpt.common.schemas import PreprocessingStatusEnum as StatusEnum
from statgpt.common.services import (
ChannelDataSetSerializer,
ChannelSerializer,
DataSetSerializer,
DataSetService,
)
from statgpt.common.services.dataset import LastCompletedVersions
from statgpt.common.settings.document import (
DimensionValueDocumentMetadataFields,
IndicatorDocumentMetadataFields,
SpecialDimensionValueDocumentMetadataFields,
)
from statgpt.common.utils import async_utils, crc32_hash_incremental_async
from statgpt.common.utils.elastic import ElasticIndex, ElasticSearchFactory, SearchResult
from statgpt.common.vectorstore import VectorStore, VectorStoreFactory
from .background_tasks import background_task
from .channel import AdminPortalChannelService as ChannelService
from .data_source import AdminPortalDataSourceService as DataSourceService
from .data_source import DataSourceTypeService
_log = logging.getLogger(__name__)
class _DataHashes(NamedTuple):
indicator_dimensions_hash: str
non_indicator_dimensions_hash: str
special_dimensions_hash: str | None
class AutoUpdateChannelResult(NamedTuple):
channel_id: int
deployment_id: str
total: int
failed: int
summary: str
failed_reasons: list[str]
class AdminPortalDataSetService(DataSetService):
def __init__(self, session: AsyncSession) -> None:
super().__init__(session, None) # No need for session lock in Admin Portal
_EXIM_SETTINGS = ExImSettings()
@staticmethod
def _get_elasticsearch_store_file_name(dataset: schemas.DataSet) -> str:
return utils.escape_invalid_filename_chars(f"{dataset.title}.jsonl")
async def _export_vector_store_data(
self,
channel: models.Channel,
res_dir: str,
auth_context: AuthContext,
latest_completed_versions: dict[int, LastCompletedVersions],
) -> None:
_log.info("Exporting vector store data...")
vector_store_factory = VectorStoreFactory(session=self._session)
# collect last completed version ids
version_ids: set[int] = set()
for versions in latest_completed_versions.values():
if versions.last_completed_version:
version_ids.add(versions.last_completed_version.version_data_id)
_log.info(f"Exporting {len(version_ids)} version(s): {sorted(version_ids)}")
collections = [
channel.available_dimensions_table_name,
channel.indicator_table_name,
channel.special_dimensions_table_name,
]
for table in collections:
vector_store = await vector_store_factory.get_vector_store(
collection_name=table,
auth_context=auth_context,
embedding_model_name=channel.llm_model,
)
vector_store_folder = os.path.join(res_dir, table.split('_', maxsplit=1)[0])
os.makedirs(vector_store_folder, exist_ok=True)
await vector_store.export_to_folder(vector_store_folder, version_ids)
_log.info("Finished exporting vector store data")
@staticmethod
async def _es_get_all(index: ElasticIndex, version_id: int) -> SearchResult:
query = {"term": {"version_id": version_id}}
res = await index.search(query=query, scroll="2m", size=10000)
all_hits = res.hits.hits
scroll_id = res.scroll_id
while scroll_id is not None:
res_scroll = await index.scroll(scroll_id=scroll_id, scroll="2m")
hits = res_scroll.hits.hits
if not hits:
break
all_hits.extend(hits)
scroll_id = res_scroll.scroll_id
res.hits.hits = all_hits
return res
async def _export_single_dataset_elastic_data(
self,
index: ElasticIndex,
dataset: schemas.DataSet,
version_id: int,
index_folder: str,
) -> None:
_log.info(f"Exporting elastic data (dataset: {dataset.title})...")
res = await self._es_get_all(index, version_id=version_id)
documents = [hit.source for hit in res.hits.hits]
file_name = self._get_elasticsearch_store_file_name(dataset)
file_path = os.path.join(index_folder, file_name)
for d in documents:
utils.write_json(
obj=d,
fp=file_path,
mode='a+',
encoding=JobsConfig.ENCODING,
indent=None,
add_newline=True,
)
_log.info(f"Exported elastic data (dataset: {dataset.title})")
async def _export_elastic_data(
self,
channel: models.Channel,
datasets: Iterable[schemas.DataSet],
latest_completed_versions: dict[int, LastCompletedVersions],
res_dir: str,
) -> None:
_log.info("Exporting elastic data...")
matching_index = await ElasticSearchFactory.get_index(channel.matching_index_name)
indicators_index = await ElasticSearchFactory.get_index(channel.indicators_index_name)
indexes = [
(JobsConfig.ES_MATCHING_DIR, matching_index),
(JobsConfig.ES_INDICATORS_DIR, indicators_index),
]
for folder, index in indexes:
index_folder = os.path.join(res_dir, folder)
os.makedirs(index_folder, exist_ok=True)
tasks = []
for dataset in datasets:
versions = latest_completed_versions[dataset.id]
if not versions.last_completed_version:
_log.warning(f"Dataset '{dataset.title}' has no completed versions. Skipping.")
continue
version_id = versions.last_completed_version.version_data_id
tasks.append(
self._export_single_dataset_elastic_data(
index, dataset, version_id, index_folder
)
)
await async_utils.gather_with_concurrency(
self._EXIM_SETTINGS.elastic_concurrency_limit, *tasks
)
_log.info("Finished exporting elastic data")
@staticmethod
def _export_datasets_config(
datasets: list[schemas.DataSet], res_dir: str
) -> dict[int, schemas.DataSource]:
data_sources = {}
data = []
for dataset in datasets:
dataset_json = dataset.model_dump(mode='json', include=JobsConfig.DATASET_FIELDS)
if dataset.data_source is None:
raise ValueError("Dataset data_source is not loaded")
dataset_json['dataSource'] = dataset.data_source.title
data.append(dataset_json)
if dataset.data_source_id not in data_sources:
data_sources[dataset.data_source_id] = dataset.data_source
data.sort(key=lambda x: x['title'])
datasets_file = os.path.join(res_dir, JobsConfig.DATASETS_FILE)
utils.write_yaml({'dataSets': data}, datasets_file)
return data_sources
@staticmethod
def _export_versions(
versions: dict[uuid.UUID, schemas.ChannelDatasetVersion], res_dir: str
) -> None:
data = {
str(ds_id): version.model_dump(mode='json', include=JobsConfig.VERSIONS_FIELDS)
for ds_id, version in versions.items()
}
datasets_file = os.path.join(res_dir, JobsConfig.VERSIONS_FILE)
utils.write_yaml({'data': data}, datasets_file)
async def export_datasets(
self,
channel: models.Channel,
res_dir: str,
scope: schemas.ExportScope,
auth_context: AuthContext,
) -> None:
channel_config = schemas.ChannelConfig.model_validate(channel.details)
datasets = await self.get_datasets_schemas(
limit=None,
offset=0,
channel_id=channel.id,
auth_context=auth_context,
allow_offline=True,
)
if scope.includes_configs():
data_sources = self._export_datasets_config(datasets, res_dir)
await DataSourceService.export_data_sources(data_sources.values(), res_dir)
if not scope.includes_indexes():
return
channel_datasets = await self.get_channel_dataset_models(
limit=None, offset=0, channel_id=channel.id
)
latest_completed_versions = await self._get_latest_successful_dataset_version(
channel_dataset_ids=[cd.id for cd in channel_datasets]
)
versions = {
next(d.id_ for d in datasets if d.id == ds_id): version.last_completed_version
for ds_id, version in latest_completed_versions.items()
if version.last_completed_version is not None
}
self._export_versions(versions, res_dir)
await self._export_vector_store_data(
channel, res_dir, auth_context, latest_completed_versions
)
if channel_config.data_query is None:
_log.info("No data query configured, skipping elastic data export")
return
indexer_version = channel_config.data_query.details.indexer_version
_log.info(f"Indexer version: {indexer_version}")
if indexer_version == schemas.IndexerVersion.hybrid:
await self._export_elastic_data(channel, datasets, latest_completed_versions, res_dir)
else:
_log.info("Skipping exporting elastic data")
async def _import_datasets(
self,
zip_file: zipfile.ZipFile,
data_sources: dict[str, models.DataSource],
update_datasets: bool,
auth_context: AuthContext,
) -> list[schemas.DataSet]:
existing_datasets = {
ds.id_: ds
for ds in await self.get_datasets_schemas(
limit=None, offset=0, allow_offline=True, auth_context=auth_context
)
}
datasets = []
with zip_file.open(JobsConfig.DATASETS_FILE) as file:
data = yaml.safe_load(file)
for dataset_cfg in data['dataSets']:
data_source = data_sources[dataset_cfg.pop('dataSource')]
dataset_cfg["data_source_id"] = data_source.id
parsed_dataset = schemas.DataSetBase.model_validate(dataset_cfg)
if dataset := existing_datasets.get(parsed_dataset.id_):
if update_datasets:
data = {
field: getattr(parsed_dataset, field)
for field in schemas.DataSetUpdateRequest.model_fields.keys()
if getattr(parsed_dataset, field) != getattr(dataset, field)
}
if data:
_log.info(f"Updating dataset '{dataset_cfg['title']}' with {data}")
update_response = await self.update(
dataset.id,
schemas.DataSetUpdateRequest.model_validate(data),
auth_context=auth_context,
)
dataset = update_response.dataset
else:
_log.info(f"Dataset '{dataset_cfg['title']}' exists and is up to date")
else:
_log.info(f"Dataset '{dataset_cfg['title']}' already exists. Skipping.")
else:
dataset = await self.create_dataset(parsed_dataset, auth_context=auth_context)
dataset.data_source = data_source # type: ignore
_log.info(f"Created dataset {dataset.title}")
datasets.append(dataset)
return datasets
async def _add_datasets_to_channel(
self, channel_id: int, datasets: list[schemas.DataSet]
) -> None:
items = [
models.ChannelDataset(
channel_id=channel_id,
dataset_id=ds.id,
)
for ds in datasets
]
self._session.add_all(items)
await self._session.commit()
async def _import_datasets_versions(
self, zip_file: zipfile.ZipFile, datasets: list[schemas.DataSet], channel_id: int
) -> dict[int, models.ChannelDatasetVersion]:
with zip_file.open(JobsConfig.VERSIONS_FILE) as file:
versions_json = yaml.safe_load(file)
datasets_dict = {ds.id: ds for ds in datasets}
channel_datasets = await self.get_channel_dataset_models(
limit=None, offset=0, channel_id=channel_id
)
versions = {}
for ch_ds in channel_datasets:
dataset = datasets_dict[ch_ds.dataset_id]
other = {}
if v := versions_json['data'].get(str(dataset.id_)):
other['creation_reason'] = "Imported from zip"
other.update(v)
else:
_log.warning(f"No version data found for dataset {dataset.title!r}")
other['creation_reason'] = "Imported from zip without version data"
version = models.ChannelDatasetVersion(
channel_dataset_id=ch_ds.id,
# `version` will be set by the DB trigger automatically
preprocessing_status=StatusEnum.IN_PROGRESS,
**other,
)
versions[ch_ds.dataset_id] = version
self._session.add_all(versions.values())
await self._session.commit()
return versions
async def _import_vector_store_tables(
self,
zip_file: zipfile.ZipFile,
channel: models.Channel,
datasets: list[schemas.DataSet],
versions: dict[int, models.ChannelDatasetVersion],
auth_context: AuthContext,
) -> None:
_log.info("Importing vector store data...")
vector_store_factory = VectorStoreFactory(session=self._session)
dataset_versions: dict[uuid.UUID, int] = {
dataset.id_: versions[dataset.id].id for dataset in datasets
}
data_sources: dict[uuid.UUID, int] = {
dataset.id_: dataset.data_source_id for dataset in datasets
}
collections = [
channel.available_dimensions_table_name,
channel.indicator_table_name,
channel.special_dimensions_table_name,
]
for table in collections:
table_folder = table.split('_', maxsplit=1)[0]
vector_store = await vector_store_factory.get_vector_store(
collection_name=table,
embedding_model_name=channel.llm_model,
auth_context=auth_context,
)
await vector_store.import_from_zipfile(
zip_file, table_folder, dataset_versions, data_sources
)
_log.info("Finished importing vector store data")
_log.info('-' * 40)
async def _import_elastic_data(
self,
zip_file: zipfile.ZipFile,
channel: models.Channel,
datasets: list[schemas.DataSet],
versions: dict[int, models.ChannelDatasetVersion],
) -> None:
_log.info("Importing elastic data...")
matching_index = await ElasticSearchFactory.get_index(
channel.matching_index_name, allow_creation=True
)
indicators_index = await ElasticSearchFactory.get_index(
channel.indicators_index_name, allow_creation=True
)
indexes = [
(JobsConfig.ES_MATCHING_DIR, matching_index),
(JobsConfig.ES_INDICATORS_DIR, indicators_index),
]
for folder, index in indexes:
for dataset in datasets:
version = versions[dataset.id]
file_name = self._get_elasticsearch_store_file_name(dataset)
file_path = f"{folder}/{file_name}"
if file_path not in zip_file.namelist():
_log.warning(f"File '{file_path}' not found in the zip archive")
continue
_log.info(f"Opening '{file_path}'")
with zip_file.open(file_path) as file:
documents: list[dict[str, str]] = []
for line in file.readlines():
doc = json.loads(line)
# Ensure dataset metadata is valid:
doc['dataset_id'] = str(dataset.id_)
doc['dataset_name'] = dataset.title
doc['version_id'] = version.id
documents.append(doc)
await index.add_bulk(documents)
_log.info("Finished importing elastic data")
_log.info('-' * 40)
async def import_datasets_and_data_sources_from_zip(
self,
channel_db: models.Channel,
zip_file: zipfile.ZipFile,
update_datasets: bool,
update_data_sources: bool,
scope: schemas.ExportScope,
auth_context: AuthContext,
) -> None:
datasets = await self._import_or_load_datasets(
zip_file, channel_db, update_datasets, update_data_sources, scope, auth_context
)
if scope.includes_indexes():
channel_config = schemas.ChannelConfig.model_validate(channel_db.details)
versions = await self._import_datasets_versions(
zip_file, datasets, channel_id=channel_db.id
)
await self._import_indexes(
zip_file, channel_db, datasets, versions, channel_config, auth_context
)
await self._mark_versions_completed(versions)
await self._session.commit()
async def _import_or_load_datasets(
self,
zip_file: zipfile.ZipFile,
channel_db: models.Channel,
update_datasets: bool,
update_data_sources: bool,
scope: schemas.ExportScope,
auth_context: AuthContext,
) -> list[schemas.DataSet]:
if scope.includes_configs():
source_service = DataSourceService(self._session)
data_sources = await source_service.import_data_sources_from_zip(
zip_file, update_data_sources
)
datasets = await self._import_datasets(
zip_file, data_sources, update_datasets, auth_context=auth_context # type: ignore
)
await self._add_datasets_to_channel(channel_id=channel_db.id, datasets=datasets)
return datasets
return await self.get_datasets_schemas(
limit=None,
offset=0,
channel_id=channel_db.id,
auth_context=auth_context,
allow_offline=True,
)
async def _import_indexes(
self,
zip_file: zipfile.ZipFile,
channel_db: models.Channel,
datasets: list[schemas.DataSet],
versions: dict[int, models.ChannelDatasetVersion],
channel_config: schemas.ChannelConfig,
auth_context: AuthContext,
) -> None:
await self._import_vector_store_tables(
zip_file, channel_db, datasets, versions, auth_context
)
await self._import_elastic_data_if_needed(
zip_file, channel_db, datasets, versions, channel_config
)
async def _import_elastic_data_if_needed(
self,
zip_file: zipfile.ZipFile,
channel_db: models.Channel,
datasets: list[schemas.DataSet],
versions: dict[int, models.ChannelDatasetVersion],
channel_config: schemas.ChannelConfig,
) -> None:
if channel_config.data_query is None:
_log.info("No data query configured, skipping data import")
return
indexer_version = channel_config.data_query.details.indexer_version
_log.info(f"Indexer version: {indexer_version}")
if indexer_version == schemas.IndexerVersion.hybrid:
await self._import_elastic_data(zip_file, channel_db, datasets, versions)
else:
_log.info("Skipping importing elastic data")
async def _mark_versions_completed(
self, versions: dict[int, models.ChannelDatasetVersion]
) -> None:
for item in versions.values():
await self._update_channel_dataset_version_status(
item, new_status=StatusEnum.COMPLETED, do_commit=False
)
async def _parse_details_field(
self, handler: base.DataSourceHandler, details: dict[str, Any]
) -> DataSetConfigType:
try:
parsed_config = handler.parse_data_set_config(details)
except ValidationError as e:
_log.info(e)
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Failed to parse 'details' field: {e}",
)
except Exception as e:
_log.info(e)
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Failed to parse 'details' field",
)
return parsed_config
@audit_action(entity_type=AuditEntityType.DATASET, action_type=AuditActionType.CREATE)
async def create_dataset(
self, data: schemas.DataSetBase, auth_context: AuthContext
) -> schemas.DataSet:
handler = await self._get_handler(data.data_source_id)
dataset_config = await self._parse_details_field(handler, data.details) # type: ignore
item = models.DataSet(
id_=data.id_,
title=data.title,
source_id=data.data_source_id,
details=dataset_config.model_dump(mode='json', by_alias=True),
)
self._session.add(item)
await self._session.flush()
dataset = await handler.get_dataset(
entity_id=item.id_,
title=item.title,
config=item.details,
auth_context=auth_context,
allow_offline=True,
)
return DataSetSerializer.db_to_schema(item, dataset)
async def load_available_datasets(
self, source_id: int, auth_context: AuthContext
) -> list[schemas.DataSetDescriptor]:
handler = await self._get_handler(source_id)
datasets = []
for ds in await handler.list_datasets(auth_context):
datasets.append(
schemas.DataSetDescriptor(
data_source_id=source_id,
id_in_source=ds.id_in_source,
title=ds.name,
description=ds.description or "",
details=ds.details.model_dump(mode="json", by_alias=True),
)
)
return datasets
async def get_dataset_config_schema(self, source_id: int) -> dict:
"""Returns JSON schema for dataset configuration."""
handler = await self._get_handler(source_id)
return handler.get_data_set_config_schema()
async def validate_config(
self, source_id: int, config: dict, auth_context: AuthContext
) -> base.DataSetValidationResult:
handler = await self._get_handler(source_id)
res = await handler.validate_dataset_config(
config, auth_context=auth_context, mode="return"
)
return res
async def get_dataset_structure(
self, source_id: int, config: dict, auth_context: AuthContext
) -> dict:
handler = await self._get_handler(source_id)
structure = await handler.get_dataset_structure(config, auth_context=auth_context)
return structure.model_dump(mode='json', by_alias=True)
@audit_action(entity_type=AuditEntityType.DATASET, action_type=AuditActionType.UPDATE)
async def update(
self, item_id: int, data: schemas.DataSetUpdateRequest, auth_context: AuthContext
) -> schemas.DataSetUpdateResponse:
item = await self.get_model_by_id(item_id, expand=True)
for attr, value in data.model_dump(exclude_unset=True, exclude={'details'}).items():
setattr(item, attr, value)
handler = await self._get_handler(item.source_id)
if data.details is not None:
dataset_config = await self._parse_details_field(handler, data.details) # type: ignore
item.details = dataset_config.model_dump(mode='json', by_alias=True)
item.updated_at = func.now()
await self._session.flush()
await self._session.refresh(item)
dataset = await handler.get_dataset(
entity_id=item.id_,
title=item.title,
config=item.details,
auth_context=auth_context,
allow_offline=True,
)
dataset_schema = DataSetSerializer.db_to_schema(item, dataset, expand=True)
channel_results = await self._propagate_config_to_channel_datasets(item, handler)
return schemas.DataSetUpdateResponse(
dataset=dataset_schema,
channel_results=channel_results,
)
@audit_action(entity_type=AuditEntityType.DATASET, action_type=AuditActionType.DELETE)
async def delete(self, item_id: int) -> schemas.DataSet:
deleted_item = await self.get_schema_by_id(
item_id,
auth_context=SystemUserAuthContext(),
allow_offline=True,
)
item = await self.get_model_by_id(item_id)
count = await self.get_channel_datasets_count(dataset_id=item.id)
if count > 0:
_log.warning(
f"The dataset(id={item_id}) is used in {count} channels, therefore it cannot be deleted."
)
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=(
f"Cannot delete dataset that is used in at least one channel."
f" Currently {count} channels are using this dataset."
),
)
_log.info(f"Deleting dataset(id={item.id}): {item.title!r}")
await self._session.delete(item)
await self._session.flush()
return deleted_item
async def _propagate_config_to_channel_datasets(
self,
dataset: models.DataSet,
handler: base.DataSourceHandler,
) -> list[schemas.ChannelDatasetUpdateResult]:
"""Propagate config changes to all channel datasets that reference this dataset.
For each channel dataset:
- If indexing is in progress -> INDEXING_IN_PROGRESS
- If no completed version exists -> NO_VERSION
- If indexing hash matches -> AUTO_UPDATED (creates new version)
- If indexing hash differs -> NEEDS_REINDEX
"""
await self._session.refresh(dataset, attribute_names=["mapped_channels"])
if not dataset.mapped_channels:
return []
results: list[schemas.ChannelDatasetUpdateResult] = []
channel_dataset_ids = [cd.id for cd in dataset.mapped_channels]
latest_versions = await self._get_latest_channel_dataset_versions(channel_dataset_ids)
last_completed_mapping = await self._get_latest_successful_channel_dataset_versions(
channel_dataset_ids=channel_dataset_ids
)
parsed_config = handler.parse_data_set_config(dataset.details)
new_config_hash = parsed_config.indexing_hash
for channel_dataset in dataset.mapped_channels:
await self._session.refresh(channel_dataset, attribute_names=["channel"])
channel = channel_dataset.channel
latest_version = latest_versions.get(channel_dataset.id)
last_completed_versions = last_completed_mapping.get(channel_dataset.id)
last_completed = (
last_completed_versions.last_completed_version if last_completed_versions else None
)
other_fields = {}
if (
latest_version
and latest_version.preprocessing_status not in StatusEnum.final_statuses()
):
status = schemas.ChannelDatasetUpdateStatus.INDEXING_IN_PROGRESS
elif last_completed is None:
status = schemas.ChannelDatasetUpdateStatus.NO_VERSION
elif new_config_hash == last_completed.indexing_config_hash:
new_version = await self._apply_config_internal(
channel_dataset, last_completed, handler, dataset.details
)
other_fields['new_version'] = new_version
status = schemas.ChannelDatasetUpdateStatus.AUTO_UPDATED
else:
status = schemas.ChannelDatasetUpdateStatus.NEEDS_REINDEX
results.append(
schemas.ChannelDatasetUpdateResult(
channel_dataset_id=channel_dataset.id,
status=status,
channel=ChannelSerializer.db_to_schema(channel),
**other_fields,
)
)
return results
async def _apply_config_internal(
self,
channel_dataset: models.ChannelDataset,
last_completed: schemas.ChannelDatasetVersion,
handler: base.DataSourceHandler,
current_config: dict[str, Any],
) -> schemas.ChannelDatasetVersion:
"""Apply config changes to a channel dataset without re-indexing.
Creates a new COMPLETED version that reuses indexed data from the
last completed version.
"""
if last_completed.resolved_config is None:
new_resolved_config = current_config
else:
new_resolved_config = handler.merge_config_with_resolved(
current_config=current_config,
resolved_config=last_completed.resolved_config,
)
parsed_config = handler.parse_data_set_config(new_resolved_config)
new_item = models.ChannelDatasetVersion(
channel_dataset_id=channel_dataset.id,
# `version` will be set by the DB trigger automatically
preprocessing_status=StatusEnum.COMPLETED,
pointer_to=last_completed.version_data_id,
creation_reason="Applied dataset config changes without re-indexing",
resolved_config=new_resolved_config,
indexing_config_hash=parsed_config.indexing_hash,
structure_metadata=last_completed.structure_metadata,
structure_hash=last_completed.structure_hash,
indicator_dimensions_hash=last_completed.indicator_dimensions_hash,
non_indicator_dimensions_hash=last_completed.non_indicator_dimensions_hash,
special_dimensions_hash=last_completed.special_dimensions_hash,
)
self._session.add(new_item)
await self._session.flush()
await self._session.refresh(new_item)
return schemas.ChannelDatasetVersion.model_validate(new_item, from_attributes=True)
async def add_dataset_to_channel(
self, channel_id: int, dataset_id: int
) -> schemas.ChannelDatasetBase:
channel: models.Channel = await ChannelService(self._session).get_model_by_id(channel_id)
dataset: models.DataSet = await self.get_model_by_id(dataset_id)
if await self.get_channel_dataset_model_or_none(
channel_id=channel_id, dataset_id=dataset_id
):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="The dataset has already been added to the channel",
)
item = models.ChannelDataset(
channel_id=channel.id,
dataset_id=dataset.id,
)
self._session.add(item)
await self._session.commit()
return schemas.ChannelDatasetBase.model_validate(item, from_attributes=True)
async def remove_channel_dataset(
self, channel_id: int, dataset_id: int, auth_context: AuthContext
) -> None:
channel: models.Channel = await ChannelService(self._session).get_model_by_id(channel_id)
dataset: models.DataSet = await self.get_model_by_id(dataset_id)
channel_dataset = await self.get_channel_dataset_model_or_none(
channel_id=channel.id, dataset_id=dataset.id
)
if not channel_dataset:
return
await self._clear_channel_dataset_data(
channel, auth_context=auth_context, dataset_id=dataset.id_, version_ids=None
)
await self._session.delete(channel_dataset)
await self._session.commit()
async def _clear_channel_dataset_data(
self,
channel: models.Channel,
auth_context: AuthContext,
*,
dataset_id: uuid.UUID | None,
version_ids: list[int] | None,
) -> None:
"""Clears all data related to a dataset or specific versions of a dataset"""
await self._clear_vector_stores(
channel, auth_context=auth_context, dataset_id=dataset_id, version_ids=version_ids
)
if ChannelService.is_channel_hybrid(channel):
await self._clear_elastic_indices(
channel, dataset_id=dataset_id, version_ids=version_ids
)
async def _clear_vector_stores(
self,
channel: models.Channel,
auth_context: AuthContext,
dataset_id: uuid.UUID | None,
version_ids: list[int] | None,
) -> None:
vector_store_factory = VectorStoreFactory(session=self._session)
collections = [
channel.indicator_table_name,
channel.special_dimensions_table_name,
channel.available_dimensions_table_name,
]
for collection_name in collections:
vector_store = await vector_store_factory.get_vector_store(
collection_name=collection_name,
auth_context=auth_context,
embedding_model_name=channel.llm_model,
)
await vector_store.remove_documents_by(dataset_id=dataset_id, version_ids=version_ids)
@staticmethod
async def _clear_elastic_indices(
channel: models.Channel, *, dataset_id: uuid.UUID | None, version_ids: list[int] | None
) -> None:
_log.info("[Elastic] Clearing existing indicators in the matching and indicators indexes")
matching_index = await ElasticSearchFactory.get_index(
channel.matching_index_name, allow_creation=True
)
indicators_index = await ElasticSearchFactory.get_index(
channel.indicators_index_name, allow_creation=True
)
if dataset_id and version_ids:
raise ValueError("Provide either dataset_id or version_ids, not both")
elif dataset_id:
query: dict = {"bool": {"must": [{"term": {"dataset_id.keyword": str(dataset_id)}}]}}
elif version_ids:
query = {"bool": {"must": [{"terms": {"version_id": version_ids}}]}}
else:
raise ValueError("Either dataset_id or version_ids must be provided")
_log.debug(f"[Elastic] Deleting documents with query: {query}")
res1 = await matching_index.delete_by_query(query=query)
res2 = await indicators_index.delete_by_query(query=query)
_log.info(f"[Elastic] Matching index cleared: {res1}")
_log.info(f"[Elastic] Indicators index cleared: {res2}")
async def _create_new_channel_dataset_version(
self,
channel_dataset_id: int,
reason: str,
preprocessing_status: StatusEnum,
resolved_config: dict | None = None,
) -> models.ChannelDatasetVersion:
item = models.ChannelDatasetVersion(
channel_dataset_id=channel_dataset_id,
# `version` will be set by the DB trigger automatically
preprocessing_status=preprocessing_status,
creation_reason=reason,
)
if resolved_config is not None:
item.resolved_config = resolved_config
self._session.add(item)
await self._session.commit()
await self._session.refresh(item)
return item
async def _update_channel_dataset_status(
self, item: models.ChannelDataset, new_status: StatusEnum, do_commit: bool = True
) -> None:
item.clearing_status = new_status
item.updated_at = func.now()
if do_commit:
await self._session.commit()
await self._session.refresh(item)
async def _update_channel_dataset_version_status(
self,
item: models.ChannelDatasetVersion,
new_status: StatusEnum,
reason_for_failure: str | None = None,
do_commit: bool = True,
) -> None:
item.preprocessing_status = new_status
item.updated_at = func.now()
if reason_for_failure:
item.reason_for_failure = reason_for_failure
if do_commit:
await self._session.commit()
await self._session.refresh(item)
async def _set_version_hashes_and_metadata(
self,
item: models.ChannelDatasetVersion,
config_hash: str,
structure_hash: str,
structure_metadata: dict,
data_hashes: _DataHashes,
) -> None:
"""Sets the structure and data hashes for the given channel dataset version."""
item.indexing_config_hash = config_hash
item.structure_metadata = structure_metadata
item.structure_hash = structure_hash
item.indicator_dimensions_hash = data_hashes.indicator_dimensions_hash
item.non_indicator_dimensions_hash = data_hashes.non_indicator_dimensions_hash
item.special_dimensions_hash = data_hashes.special_dimensions_hash