Repository navigation
Expand file tree
/
Copy pathdatabase.py
More file actions
3420 lines (3071 loc) · 125 KB
/
Copy pathdatabase.py
File metadata and controls
3420 lines (3071 loc) · 125 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
# AudioMuse-AI - https://github.com/NeptuneHub/AudioMuse-AI
# Copyright (C) 2025 NeptuneHub
# SPDX-License-Identifier: AGPL-3.0-only
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License v3.0. See the LICENSE file
# in the project root or <https://github.com/NeptuneHub/AudioMuse-AI/blob/main/LICENSE>
"""Postgres data-access layer for the whole application.
Owns the per-request connection (via Flask g), the embedded-server lifecycle,
the init_db schema bootstrap, and every read/write helper for tasks, track
analysis and embeddings, projections, and alchemy anchors/radios.
Main Features:
* Connection management plus init_db table/index creation and migrations; a
worker job holds ONE app context for its whole run, so get_db drops a cached
connection the server closed and reconnects on the next call.
* Task-status and history persistence with sanitized fields and capped rows; a
status write the row refuses ends the transaction with a ROLLBACK.
* record_root_recap is the ONE root-finish bookkeeping (the task_history line
and the collapse to a single recap row) shared by save_task_status, the
worker's terminal write and the migration handshake recovery. It must run
AFTER the terminal row is committed: record_task_history rolls back on
failure, and in the worker that rollback used to undo the verdict itself.
* stage_pending_task_row is the one way to stage a placeholder row a later
taskqueue.enqueue on the same transaction adopts (True only for a row this
call created).
* MAIN_TASK_START_LOCK_KEY serializes the check-cleanup-claim sequence of a
main-task start; SESSION scoped on purpose, since the cleanup commits in the
middle of it and a transaction lock would be released by that commit.
* The start filters come from task_types: the inline online runs, the restart
handshake and the migration PLANNER are deliberately not blocking (none is
catalogue work); server_sweep and the plugin tasks DO block, since they write
the mappings a cleaning or a migration rewrites. Excluding nothing once made
a restart handshake answer 409 to a cleaning the user had just asked for.
* _CONNECT_OPTIONS goes on every app connection: statement_timeout caps a
runaway query at 10 minutes and max_parallel_workers_per_gather=0 forces
SERIAL plans, because a parallel plan's shared-memory segment in /dev/shm
(small in containers) made the analysis work map scan die with DiskFull.
* Embedding, projection, and alchemy CRUD shared by workers and the web app.
* pgserver skips the embedded shutdown while its handle list names another pid
(a supervisor killed hard leaves one), so the list is pruned under its lock
to live supervisors; a start gets a 120 s pg_ctl timeout and a failed one
forgets pgserver's cached instance so a retry really restarts.
"""
import json
import logging
import os
import sys
import time
import uuid
from contextlib import contextmanager, nullcontext
from pathlib import Path
import numpy as np
import psutil
import psycopg2
from flask import g
from psycopg2 import sql
from psycopg2.extras import DictCursor, Json, execute_values
import config
import task_types
logger = logging.getLogger(__name__)
from tz_helper import UTC_NOW_SQL
from sanitization import sanitize_db_field, sanitize_string_for_db, sanitize_for_log
from config import (
TASK_STATUS_NEW,
TASK_STATUS_PENDING,
TASK_STATUS_STARTED,
TASK_STATUS_PROGRESS,
TASK_STATUS_SUCCESS,
TASK_STATUS_FAILURE,
TASK_STATUS_REVOKED,
TASK_STATUS_TERMINAL,
)
_TERMINAL_STATUSES = list(TASK_STATUS_TERMINAL)
MAX_LOG_ENTRIES_STORED = 10
TEXT_SEARCH_QUERIES_DDL = """
CREATE TABLE IF NOT EXISTS text_search_queries (
id SERIAL PRIMARY KEY,
query_text TEXT NOT NULL,
score REAL NOT NULL,
rank INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(rank)
)
"""
TEXT_SEARCH_QUERIES_RANK_INDEX_DDL = (
"CREATE INDEX IF NOT EXISTS idx_text_search_queries_rank "
"ON text_search_queries(rank)"
)
DEFAULT_TEXT_SEARCH_QUERIES = [
"female vocal romantic trap",
"synth indie pop raspy",
"sad hard rock male vocal",
"funk falsetto energetic",
"groovy sax blues",
"classical relaxed piano",
"belting jazz happy",
"tabla afrobeat fast-paced",
"harmonized vocals slow-paced electronica",
"autotuned gospel excited",
"breathy aggressive house",
"smooth folk mid-tempo",
"deep voice r&b dark",
"punk guitar angry",
"metal choir dreamy",
"chant reggae trumpet",
"high-pitched brass hip-hop",
"disco whispered drum machine",
"happy whispered indie pop",
"synth energetic raspy",
"rock slow-paced cello",
"falsetto jazz excited",
"r&b male vocal romantic",
"harmonized vocals dark trap",
"smooth blues sax",
"high-pitched fast-paced soul",
"female vocal sad hip-hop",
"congas aggressive soul",
"mid-tempo afrobeat autotuned",
"belting funk groovy",
"angry alternative breathy",
"gospel choir steelpan",
"viola relaxed folk",
"dreamy rhodes metal",
"acoustic guitar country chant",
"deep voice orchestra reggae",
"fast-paced synth progressive rock",
"hard rock raspy romantic",
"fast-paced electric guitar progressive rock",
"hard rock aggressive breathy",
"rock high-pitched energetic",
"autotuned energetic hip-hop",
"raspy fast-paced blues",
"belting electronica energetic",
"whispered indie pop aggressive",
"harmonized vocals aggressive synth",
"orchestra whispered romantic",
"belting mid-tempo progressive rock",
"autotuned pop mid-tempo",
"pop energetic synthesizer",
"POP viola with female vocalist",
]
DEFAULT_TEXT_SEARCH_STEERING = {
"female vocal sad hip-hop": [
{"term": "hip hop", "direction": "more", "weight": 3.0},
{"term": "sad", "direction": "more", "weight": 10.0},
],
"autotuned pop mid-tempo": [
{"term": "pop", "direction": "more", "weight": 10.0},
],
"whispered indie pop aggressive": [
{"term": "indie pop", "direction": "more", "weight": 5.0},
],
"classical relaxed piano": [
{"term": "relaxed", "direction": "more", "weight": 10.0},
],
"POP viola with female vocalist": [
{"term": "viola", "direction": "more", "weight": 10.0},
],
}
MAIN_TASK_START_LOCK_KEY = 5512740318664902
_ADVISORY_LOCK_SQL = "SELECT pg_advisory_lock(%s)"
_ADVISORY_UNLOCK_SQL = "SELECT pg_advisory_unlock(%s)"
GLOBAL_CANCEL_EPOCH_KEY = 'global_cancel_epoch'
SELF_MANAGED_TASK_TYPES = task_types.SELF_MANAGED_TASK_TYPES
SELF_MANAGED_TASK_TYPE_PREFIXES = task_types.SELF_MANAGED_TASK_TYPE_PREFIXES
_BLOCKING_TASK_TYPE_PATTERNS = [
prefix + '%' for prefix in task_types.BLOCKING_TASK_TYPE_PREFIXES
]
_PLUGIN_TASK_NAMESPACE = 'audiomuse_plugins'
_PLUGIN_OWNED_TASK_TYPE_RE = r'^plugin\.(audiomuse_plugins\.[^.]+\.|[^.]+\.[^.]+$)'
NON_BLOCKING_TASK_TYPES = task_types.NON_BLOCKING_TASK_TYPES
INLINE_FLASK_TASK_TYPES = task_types.INLINE_FLASK_TASK_TYPES
USERS_PASSWORD_CHANGED_AT_DDL = (
"ALTER TABLE IF EXISTS audiomuse_users "
"ADD COLUMN IF NOT EXISTS password_changed_at TIMESTAMP"
)
MAP_PROJECTION_CACHE = None
_embedded_server = None
_CONNECT_OPTIONS = '-c statement_timeout=600000 -c max_parallel_workers_per_gather=0'
class ConnectionLostError(psycopg2.OperationalError):
pass
def get_db():
cached = g.get('db')
if cached is not None and cached.closed:
g.pop('db', None)
if cached.closed == 2:
logger.error(
"The database connection was dropped by the server while this app "
"context held it; failing this unit of work rather than finishing "
"it on a second connection."
)
raise ConnectionLostError("database connection lost, retry the operation")
logger.warning("Cached database connection was closed; reconnecting.")
if 'db' not in g:
try:
g.db = connect_raw()
except psycopg2.OperationalError:
logger.exception("Failed to connect to database")
raise
return g.db
def close_db(e=None):
db = g.pop('db', None)
if db is not None:
db.close()
def _holds_embedded_handle(pid):
try:
if int(pid) == os.getpid():
return True
proc = psutil.Process(int(pid))
argv = proc.cmdline() or []
exe = proc.exe() or ''
except Exception:
return False
if any(str(arg).startswith('--role=') for arg in argv[1:]):
return False
return bool(exe) and (
os.path.normcase(os.path.realpath(exe))
== os.path.normcase(os.path.realpath(sys.executable))
)
def _drop_dead_handles(server):
handles = server.global_process_id_list
lock = getattr(server, '_lock', None)
try:
with (lock if lock is not None else nullcontext()):
pids = handles.get()
alive = [pid for pid in pids if _holds_embedded_handle(pid)]
if alive != pids:
handles.put(alive)
except Exception:
logger.exception("Could not prune the embedded PostgreSQL handle list")
_EMBEDDED_PG_START_TIMEOUT_SECONDS = 120
def _patch_pgserver_start_timeout():
try:
import pgserver.postgres_server as ps
except ImportError:
return
original = getattr(ps, "pg_ctl", None)
if original is None or getattr(ps, "_audiomuse_pg_ctl_patched", False):
return
timeout = _EMBEDDED_PG_START_TIMEOUT_SECONDS
def pg_ctl(args, **kwargs):
if args and "start" in args:
if kwargs.get("timeout") is None or kwargs["timeout"] < timeout:
kwargs["timeout"] = timeout
env = dict(os.environ if kwargs.get("env") is None else kwargs["env"])
env.setdefault("PGCTLTIMEOUT", str(timeout))
kwargs["env"] = env
return original(args, **kwargs)
ps.pg_ctl = pg_ctl
ps._audiomuse_pg_ctl_patched = True
def start_embedded(data_dir):
global _embedded_server
import pgserver
_patch_pgserver_start_timeout()
try:
_embedded_server = pgserver.get_server(data_dir)
except Exception:
_forget_pgserver_instance(pgserver, data_dir)
raise
_drop_dead_handles(_embedded_server)
return _embedded_server.get_uri()
def _forget_pgserver_instance(pgserver, data_dir):
try:
pgserver.PostgresServer._instances.pop(Path(data_dir).expanduser().resolve(), None)
except Exception:
logger.debug("Could not drop the cached pgserver instance", exc_info=True)
def ensure_embedded_running(data_dir):
global _embedded_server
if _embedded_server is None:
return start_embedded(data_dir)
import pgserver
_forget_pgserver_instance(pgserver, data_dir)
_patch_pgserver_start_timeout()
_embedded_server = pgserver.get_server(data_dir)
_drop_dead_handles(_embedded_server)
return _embedded_server.get_uri()
def stop_embedded():
global _embedded_server
if _embedded_server is not None:
_drop_dead_handles(_embedded_server)
_embedded_server.cleanup()
_embedded_server = None
def _build_task_note(task_type, details_obj):
if not isinstance(details_obj, dict):
details_obj = {}
t = (task_type or '').lower()
if task_types.matches(t, prefixes=task_types.PREFIXES):
return ''
try:
if 'analysis' in t:
songs = details_obj.get('tracks_analyzed')
songs = int(songs) if isinstance(songs, (int, float)) else 0
return f"Songs analyzed: {songs}"
if 'clean' in t:
for k in (
'tracks_deleted',
'orphans_removed',
'songs_cleaned',
'tracks_removed',
'deleted_count',
'cleaned_tracks',
):
v = details_obj.get(k)
if isinstance(v, (int, float)):
return f"Songs cleaned: {int(v)}"
return ''
if 'cluster' in t:
sampled = (
(details_obj.get('best_params') or {}).get('initial_subset_size')
if isinstance(details_obj.get('best_params'), dict)
else None
)
if sampled is None:
sampled = details_obj.get('sampled_songs') or details_obj.get('num_sampled_songs')
n_clusters = details_obj.get('num_playlists_created') or details_obj.get('num_clusters')
parts = []
if sampled:
parts.append(f"sampled: {int(sampled)}")
if n_clusters:
parts.append(f"clusters: {int(n_clusters)}")
return ' | '.join(parts)
except Exception as e:
logger.debug(f"task note builder failed for type={task_type}: {e}")
return ''
def record_task_history(task_id, task_type, status, duration_seconds=None, note=None,
details=None, conn=None):
if not task_id:
return
try:
db = conn or get_db()
if note is None:
details_obj = details if isinstance(details, dict) else {}
details_obj = dict(details_obj)
details_obj['_task_id'] = task_id
note = _build_task_note(task_type, details_obj) or ''
if not note:
note = details_obj.get('status_message') or details_obj.get('message') or ''
with db.cursor() as cur:
cur.execute("SELECT 1 FROM task_history WHERE task_id = %s LIMIT 1", (task_id,))
if cur.fetchone():
return
cur.execute(
f"""
INSERT INTO task_history (task_id, task_type, status, duration_seconds, note, recorded_at)
VALUES (%s, %s, %s, %s, %s, {UTC_NOW_SQL})
""",
(task_id, task_type, status, duration_seconds, note),
)
cur.execute(
"""
DELETE FROM task_history
WHERE id IN (
SELECT id FROM (
SELECT id,
ROW_NUMBER() OVER (
PARTITION BY task_type ORDER BY recorded_at DESC, id DESC
) AS type_rank
FROM task_history
) AS ranked
WHERE type_rank > %s
)
""",
(max(1, config.TASK_HISTORY_MAX_ROWS_PER_TYPE),),
)
db.commit()
with db.cursor() as cur:
cur.execute("SELECT to_regclass('plugins') IS NOT NULL")
if cur.fetchone()[0]:
cur.execute(
"""
DELETE FROM task_history
WHERE task_type ~ %s
AND CASE WHEN split_part(task_type, '.', 2) = %s
THEN split_part(task_type, '.', 3)
ELSE split_part(task_type, '.', 2)
END NOT IN (SELECT id FROM plugins)
""",
(_PLUGIN_OWNED_TASK_TYPE_RE, _PLUGIN_TASK_NAMESPACE),
)
db.commit()
except Exception as e:
logger.warning(f"record_task_history failed for {task_id}: {e}")
try:
db.rollback()
except Exception:
pass
def _normalize_task_details(details, status):
if not isinstance(details, dict):
return
if status == TASK_STATUS_SUCCESS:
details.pop('log_storage_info', None)
if not isinstance(details.get('log'), list) or not details.get('log'):
details['log'] = ["Task completed successfully."]
return
if not isinstance(details.get('log'), list):
return
log_list = details['log']
if len(log_list) <= MAX_LOG_ENTRIES_STORED:
details.pop('log_storage_info', None)
return
original_log_length = len(log_list)
details['log'] = log_list[-MAX_LOG_ENTRIES_STORED:]
details['log_storage_info'] = (
f"Log in DB truncated to last {MAX_LOG_ENTRIES_STORED} entries. Original length: {original_log_length}."
)
def _maybe_record_task_history(db, task_id, task_type, status, parent_task_id, details, current_unix_time):
if parent_task_id is not None:
return
if status not in (TASK_STATUS_SUCCESS, TASK_STATUS_FAILURE, TASK_STATUS_REVOKED):
return
if not task_type or task_type == 'unknown' or task_type in task_types.SIDE_JOB_TASK_TYPES:
return
duration_s = None
try:
with db.cursor() as hist_cur:
hist_cur.execute(
"SELECT start_time, end_time FROM task_status WHERE task_id = %s",
(task_id,),
)
row = hist_cur.fetchone()
if row and row[0] is not None:
end = row[1] if row[1] is not None else current_unix_time
duration_s = max(0.0, float(end) - float(row[0]))
except Exception:
pass
record_task_history(
task_id, task_type, status, duration_seconds=duration_s, details=details, conn=db,
)
def collapse_finished_task(db, task_id, task_type, parent_task_id, status):
if parent_task_id is not None or not task_type:
return 0
if status not in (TASK_STATUS_SUCCESS, TASK_STATUS_FAILURE, TASK_STATUS_REVOKED):
return 0
from taskqueue.sql import CONTROL_TASK_TYPE, TERMINAL_AND_NOT_A_LIVE_PARENTS_CHILD
if task_type == CONTROL_TASK_TYPE or task_type in task_types.SIDE_JOB_TASK_TYPES:
return 0
try:
with db.cursor() as cur:
cur.execute(
"DELETE FROM task_status WHERE task_id <> %s AND "
+ TERMINAL_AND_NOT_A_LIVE_PARENTS_CHILD,
(task_id,),
)
deleted = cur.rowcount
db.commit()
except Exception:
try:
db.rollback()
except Exception:
logger.debug("Rollback after a failed task collapse failed", exc_info=True)
logger.exception("Could not collapse finished task %s", sanitize_for_log(task_id))
return 0
if deleted:
logger.info(
"Task %s finished (%s); dropped %d rows, keeping only its one-line recap.",
sanitize_for_log(task_id), sanitize_for_log(status), deleted,
)
return deleted
def record_root_recap(db, task_id, task_type, parent_task_id, status, details, now=None):
if parent_task_id is not None:
return 0
_maybe_record_task_history(
db, task_id, task_type, status, parent_task_id, details,
time.time() if now is None else now,
)
return collapse_finished_task(db, task_id, task_type, parent_task_id, status)
def save_task_status(
task_id,
task_type,
status=TASK_STATUS_PENDING,
parent_task_id=None,
sub_type_identifier=None,
progress=0,
details=None,
raise_on_error=False,
):
try:
db = get_db()
except ConnectionLostError:
db = get_db()
current_unix_time = time.time()
if details is not None:
_normalize_task_details(details, status)
details_json = json.dumps(details) if details is not None else None
written = False
cur = db.cursor()
try:
cur.execute(
"""
INSERT INTO task_status (task_id, parent_task_id, task_type, sub_type_identifier, status, progress, details, timestamp, start_time, end_time)
SELECT %s, %s, %s, %s, %s, %s, %s, NOW(), %s, CASE WHEN %s = ANY(%s) THEN %s ELSE NULL END
WHERE %s IS NULL
OR EXISTS (
SELECT 1 FROM task_status AS parent
WHERE parent.task_id = %s
AND parent.status <> ALL(%s)
)
OR EXISTS (SELECT 1 FROM task_status AS existing WHERE existing.task_id = %s)
ON CONFLICT (task_id) DO UPDATE SET
status = EXCLUDED.status,
parent_task_id = COALESCE(EXCLUDED.parent_task_id, task_status.parent_task_id),
sub_type_identifier = COALESCE(EXCLUDED.sub_type_identifier, task_status.sub_type_identifier),
progress = EXCLUDED.progress,
details = EXCLUDED.details,
timestamp = NOW(),
start_time = COALESCE(task_status.start_time, %s),
end_time = CASE
WHEN EXCLUDED.status = ANY(%s) AND task_status.end_time IS NULL
THEN %s
ELSE task_status.end_time
END,
-- A terminal row is a recap, never a runnable job. Tasks write
-- their own terminal row through here, so the worker's finish
-- statement is a safety net that mostly does not fire and the
-- payload survived: a clustering batch's kwargs carry the whole
-- lightweight genre map, and secrets aside, that is hundreds of
-- megabytes of WAL-logged, replicated, backed-up dead weight
-- kept for as long as the one-line recap.
func = CASE WHEN EXCLUDED.status = ANY(%s) THEN NULL ELSE task_status.func END,
payload = CASE
WHEN EXCLUDED.status = ANY(%s) THEN NULL
ELSE task_status.payload
END
WHERE COALESCE(task_status.status, '') <> ALL(%s)
RETURNING parent_task_id
""",
(
task_id,
parent_task_id,
task_type,
sub_type_identifier,
status,
progress,
details_json,
current_unix_time,
status,
_TERMINAL_STATUSES,
current_unix_time,
parent_task_id,
parent_task_id,
_TERMINAL_STATUSES,
task_id,
current_unix_time,
_TERMINAL_STATUSES,
current_unix_time,
_TERMINAL_STATUSES,
_TERMINAL_STATUSES,
_TERMINAL_STATUSES,
),
)
written = cur.rowcount > 0
stored_parent_task_id = parent_task_id
if written:
written_row = cur.fetchone()
if written_row is not None:
stored_parent_task_id = written_row[0]
db.commit()
else:
db.rollback()
except psycopg2.Error:
written = False
logger.exception(f"DB Error saving task status for {task_id}")
try:
db.rollback()
logger.info(f"DB transaction rolled back for task status update of {task_id}.")
except psycopg2.Error:
logger.exception(f"DB Error during rollback for task status {task_id}")
if raise_on_error:
raise
finally:
cur.close()
if not written:
logger.info(
"Discarded the %s report for task %s (parent %s): the row is already "
"terminal, or it does not exist and its parent is missing or terminal. A "
"terminal row is the queue's verdict and no later report may regress it.",
status, task_id, parent_task_id,
)
return False
try:
record_root_recap(
db, task_id, task_type, stored_parent_task_id, status, details, current_unix_time
)
except Exception:
logger.exception(
"Wrote %s for task %s but could not record its history or collapse the table",
status, sanitize_for_log(task_id),
)
return True
STAGE_PENDING_TASK_ROW_SQL = (
"INSERT INTO task_status "
"(task_id, task_type, status, progress, details, timestamp, start_time) "
"VALUES (%s, %s, %s, 0, %s, NOW(), %s) "
"ON CONFLICT (task_id) DO NOTHING"
)
_STAGE_SAVEPOINT = "audiomuse_stage_task_row"
def stage_pending_task_row(cur, task_id, task_type, details, start_time=None):
payload = json.dumps(details if isinstance(details, dict) else {'message': str(details)})
cur.execute(f"SAVEPOINT {_STAGE_SAVEPOINT}")
try:
cur.execute(
STAGE_PENDING_TASK_ROW_SQL,
(
task_id,
task_type,
TASK_STATUS_NEW,
payload,
time.time() if start_time is None else start_time,
),
)
except psycopg2.errors.UniqueViolation:
cur.execute(f"ROLLBACK TO SAVEPOINT {_STAGE_SAVEPOINT}")
logger.info(
"Not staging %s row %s: another live row already holds the slot.",
sanitize_for_log(task_type), sanitize_for_log(task_id),
)
return False
created = cur.rowcount > 0
cur.execute(f"RELEASE SAVEPOINT {_STAGE_SAVEPOINT}")
if not created:
logger.info(
"Not staging %s row %s: that task id is already in task_status, so this "
"call created nothing and does not own the slot.",
sanitize_for_log(task_type), sanitize_for_log(task_id),
)
return created
def get_task_info_from_db(task_id):
db = get_db()
cur = db.cursor(cursor_factory=DictCursor)
cur.execute(
"""
SELECT
task_id, parent_task_id, task_type, sub_type_identifier, status, progress, details, timestamp, start_time, end_time
FROM task_status
WHERE task_id = %s
""",
(task_id,),
)
row = cur.fetchone()
cur.close()
if not row:
return None
row_dict = dict(row)
current_unix_time = time.time()
start_time = row_dict.get('start_time')
end_time = row_dict.get('end_time')
if start_time is None:
row_dict['running_time_seconds'] = 0.0
else:
effective_end_time = end_time if end_time is not None else current_unix_time
row_dict['running_time_seconds'] = max(0, effective_end_time - start_time)
return row_dict
def get_task_statuses(task_ids):
ids = [str(t) for t in task_ids if t]
if not ids:
return {}
db = get_db()
cur = db.cursor()
try:
cur.execute(
"SELECT task_id, status FROM task_status WHERE task_id = ANY(%s)", (ids,)
)
return {row[0]: row[1] for row in cur.fetchall()}
finally:
cur.close()
def get_score_data_by_ids(item_ids_list):
if not item_ids_list:
return []
conn = get_db()
cur = conn.cursor(cursor_factory=DictCursor)
query = """
SELECT s.item_id, s.title, s.author, s.album, s.album_artist, s.tempo, s.key, s.scale, s.mood_vector, s.energy, s.other_features, s.year, s.rating, s.file_path
FROM score s
WHERE s.item_id IN %s
"""
guarded = getattr(conn, 'autocommit', False) is False
try:
if guarded:
cur.execute("SAVEPOINT score_data_by_ids")
cur.execute(query, (tuple(item_ids_list),))
rows = cur.fetchall()
if guarded:
cur.execute("RELEASE SAVEPOINT score_data_by_ids")
except Exception:
logger.exception("Error fetching score data by IDs")
rows = []
if guarded:
try:
cur.execute("ROLLBACK TO SAVEPOINT score_data_by_ids")
except Exception:
logger.exception("Could not roll back to the savepoint after the failed score data fetch")
finally:
cur.close()
return [dict(row) for row in rows]
def get_tracks_by_ids(item_ids_list):
if not item_ids_list:
return []
conn = get_db()
cur = conn.cursor(cursor_factory=DictCursor)
item_ids_str = [str(item_id) for item_id in item_ids_list]
query = """
SELECT s.item_id, s.title, s.author, s.album, s.album_artist, s.tempo, s.key, s.scale, s.mood_vector, s.energy, s.other_features, s.year, s.rating, s.file_path, e.embedding
FROM score s
LEFT JOIN embedding e ON s.item_id = e.item_id
WHERE s.item_id IN %s
"""
cur.execute(query, (tuple(item_ids_str),))
rows = cur.fetchall()
cur.close()
processed_rows = []
for row in rows:
row_dict = dict(row)
if row_dict.get('embedding'):
row_dict['embedding_vector'] = np.nan_to_num(np.frombuffer(row_dict['embedding'], dtype=np.float32), nan=0.0, posinf=0.0, neginf=0.0)
else:
row_dict['embedding_vector'] = np.array([])
processed_rows.append(row_dict)
return processed_rows
def load_map_projection(index_name, force_reload=False):
global MAP_PROJECTION_CACHE
if (
not force_reload
and MAP_PROJECTION_CACHE
and MAP_PROJECTION_CACHE.get('index_name') == index_name
):
logger.info(f"Map projection '{index_name}' already loaded in cache. Skipping reload.")
return MAP_PROJECTION_CACHE.get('id_map'), MAP_PROJECTION_CACHE.get('projection')
logger.info(f"Attempting to load map projection '{index_name}' from database into memory...")
conn = get_db()
cur = conn.cursor()
try:
cur.execute(
"SELECT projection_data, id_map_json FROM map_projection_data WHERE index_name = %s",
(index_name,),
)
row = cur.fetchone()
if row and row[0] is not None:
proj_blob, id_map_json = row[0], row[1]
else:
from tasks.index_build_helpers import (
collect_segment_names,
reassemble_segmented_id_map,
segment_like_pattern,
)
cur.execute(
"SELECT index_name, projection_data, id_map_json FROM map_projection_data WHERE index_name LIKE %s ESCAPE E'\\\\'",
(segment_like_pattern(index_name),),
)
candidates = cur.fetchall()
if not candidates:
logger.warning(
f"Map projection '{index_name}' not found in the database. Cache will be empty."
)
return None, None
try:
total_expected, parsed = collect_segment_names(
index_name, [row[0] for row in candidates]
)
except ValueError:
logger.exception(
f"Map projection segment total mismatch for '{index_name}'. Aborting load."
)
return None, None
rows_by_name = {row[0]: row for row in candidates}
parts = [
(part_no, rows_by_name[part_name][1], rows_by_name[part_name][2])
for part_no, part_name in parsed
]
if total_expected is None or len(parts) != total_expected:
logger.error(
f"Incomplete map projection segments for '{index_name}': expected {total_expected}, found {len(parts)}. Aborting load."
)
return None, None
parts.sort(key=lambda p: p[0])
proj_blob = b"".join(bytes(p[1]) for p in parts if p[1])
id_map_json = reassemble_segmented_id_map((p[0], p[2]) for p in parts)
proj = np.frombuffer(proj_blob, dtype=np.float32)
if proj.size % 2 == 0:
proj = proj.reshape((-1, 2))
id_map = json.loads(id_map_json)
MAP_PROJECTION_CACHE = {'index_name': index_name, 'id_map': id_map, 'projection': proj}
logger.info(
f"Map projection '{index_name}' with {len(id_map)} items loaded successfully into memory."
)
return id_map, proj
except Exception:
logger.exception("Failed to load map projection")
return None, None
finally:
cur.close()
def _valid_year(year_value):
if 1000 <= year_value <= 2100:
return year_value
return None
def _parse_year_parts(parts):
try:
if len(parts[0]) == 4:
result = _valid_year(int(parts[0]))
if result is not None:
return result
if len(parts[2]) == 4:
result = _valid_year(int(parts[2]))
if result is not None:
return result
if len(parts[2]) == 2:
year = int(parts[2])
year += 2000 if year < 30 else 1900
return _valid_year(year)
except (ValueError, TypeError, IndexError):
pass
return None
def _parse_year_from_date(year_value):
if year_value is None:
return None
year_str = str(year_value).strip()
if not year_str:
return None
try:
result = _valid_year(int(year_str))
if result is not None:
return result
except (ValueError, TypeError):
pass
parts = year_str.replace('/', '-').split('-')
if len(parts) == 3:
return _parse_year_parts(parts)
return None
def _clamp_rating(rating):
if rating is None:
return None
try:
rating = int(rating)
if rating < 0 or rating > 5:
return None
return rating
except (ValueError, TypeError):
return None
def _persist_hyperbolic_inline(item_id, embedding_vector, cur):
try:
from tasks.hyperbolic_manager import compute_hyperbolic_projection
proj, radius = compute_hyperbolic_projection(embedding_vector, auto_calibrate=False)
if proj is None or radius is None:
return
embedding_blob = np.asarray(proj, dtype=np.float32).tobytes()
cur.execute(
"""
INSERT INTO embedding (item_id, poincare_embedding, hyperbolic_radius)
VALUES (%s, %s, %s)
ON CONFLICT (item_id) DO UPDATE SET
poincare_embedding = EXCLUDED.poincare_embedding,
hyperbolic_radius = EXCLUDED.hyperbolic_radius
""",
(item_id, psycopg2.Binary(embedding_blob), float(radius)),
)
except Exception:
logger.debug(
"Could not persist hyperbolic projection inline for %s", item_id, exc_info=True
)
def save_track_analysis_and_embedding(
item_id,
title,
author,
tempo,
key,
scale,
moods,
embedding_vector,
energy=None,
other_features=None,
album=None,
album_artist=None,
year=None,
rating=None,