Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
/*-------------------------------------------------------------------------
 *
 * worker.c
 *      Background worker implementation for async embedding generation
 *
 * This file implements the background worker that processes the embedding
 * queue and generates embeddings using configured providers.
 *
 * Copyright (c) 2025 - 2026, pgEdge, Inc.
 *
 *-------------------------------------------------------------------------
 */
#include "vectorizer/pgedge_vectorizer.h"
 
#include <time.h>
 
#include "commands/dbcommands.h"
#include "pgstat.h"
#include "postmaster/interrupt.h"
#include "storage/proc.h"
#include "tcop/tcopprot.h"
#include "utils/memutils.h"
#include "utils/ps_status.h"
 
/* Signal flags */
static volatile sig_atomic_t got_sigterm = false;
static volatile sig_atomic_t got_sighup = false;
 
/* Last cleanup timestamp */
static time_t last_cleanup_time = 0;
 
/* Forward declarations */
static void worker_sigterm(SIGNAL_ARGS);
static void worker_sighup(SIGNAL_ARGS);
static void process_queue_batch(int worker_id);
static void cleanup_completed_items(int worker_id);
static void update_embedding(int64 chunk_id, const char *chunk_table,
                             const float *embedding, int dim);
 
/*
 * Signal handler for SIGTERM
 */
static void
worker_sigterm(SIGNAL_ARGS)
{
    int save_errno = errno;
    got_sigterm = true;
    SetLatch(MyLatch);
    errno = save_errno;
}
 
/*
 * Signal handler for SIGHUP
 */
static void
worker_sighup(SIGNAL_ARGS)
{
    int save_errno = errno;
    got_sighup = true;
    SetLatch(MyLatch);
    errno = save_errno;
}
 
/*
 * Register background workers
 *
 * Called during _PG_init when shared_preload_libraries is processed.
 */
void
register_background_workers(void)
{
    BackgroundWorker worker;
 
    for (int i = 0; i < pgedge_vectorizer_num_workers; i++)
    {
        memset(&worker, 0, sizeof(BackgroundWorker));
 
        /* Set worker properties */
        worker.bgw_flags = BGWORKER_SHMEM_ACCESS |
                           BGWORKER_BACKEND_DATABASE_CONNECTION;
        worker.bgw_start_time = BgWorkerStart_RecoveryFinished;
        worker.bgw_restart_time = 10;  /* Restart after 10 seconds if crashes */
 
        snprintf(worker.bgw_library_name, BGW_MAXLEN, "postgres");
        snprintf(worker.bgw_function_name, BGW_MAXLEN, "pgedge_vectorizer_worker_main");
        snprintf(worker.bgw_name, BGW_MAXLEN, "pgedge_vectorizer worker %d", i + 1);
        snprintf(worker.bgw_type, BGW_MAXLEN, "pgedge_vectorizer");
 
        worker.bgw_main_arg = Int32GetDatum(i);
        worker.bgw_notify_pid = 0;
 
        RegisterBackgroundWorker(&worker);
    }
}
 
/*
 * Background worker main entry point
 */
PGDLLEXPORT void
pgedge_vectorizer_worker_main(Datum main_arg)
{
    int worker_id = DatumGetInt32(main_arg);
    char dbname[NAMEDATALEN];
    char *db_list;
    char *db_name;
    char *db_copy;
    int db_count = 0;
 
    /* Setup signal handlers */
    pqsignal(SIGTERM, worker_sigterm);
    pqsignal(SIGHUP, worker_sighup);
 
    /* We're now ready to receive signals */
    BackgroundWorkerUnblockSignals();
 
    /* Check if databases are configured */
    if (pgedge_vectorizer_databases == NULL || pgedge_vectorizer_databases[0] == '\0')
    {
        elog(LOG, "pgedge_vectorizer worker %d: no databases configured in rudb_ai.databases, sleeping",
             worker_id + 1);
 
        /* Sleep indefinitely, checking periodically for config changes */
        while (!got_sigterm)
        {
            int rc;
 
            if (got_sighup)
            {
                got_sighup = false;
                ProcessConfigFile(PGC_SIGHUP);
 
                /* Check if databases were configured */
                if (pgedge_vectorizer_databases != NULL && pgedge_vectorizer_databases[0] != '\0')
                    break;
            }
 
            rc = WaitLatch(MyLatch,
                           WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
                           60000L, /* Check every minute */
                           PG_WAIT_EXTENSION);
 
            ResetLatch(MyLatch);
 
            if (rc & WL_POSTMASTER_DEATH)
                proc_exit(1);
        }
 
        if (got_sigterm)
            proc_exit(0);
    }
 
    /* Parse database list and select one for this worker */
    db_list = pstrdup(pgedge_vectorizer_databases);
    db_copy = db_list;
 
    /* Count databases */
    while ((db_name = strtok(db_copy, ",")) != NULL)
    {
        db_copy = NULL;
        db_count++;
    }
 
    if (db_count == 0)
    {
        elog(LOG, "pgedge_vectorizer worker %d: empty database list, exiting",
             worker_id + 1);
        proc_exit(0);
    }
 
    /* Select database for this worker (round-robin) */
    pfree(db_list);
    db_list = pstrdup(pgedge_vectorizer_databases);
    db_copy = db_list;
 
    for (int i = 0; i <= (worker_id % db_count); i++)
    {
        db_name = strtok(db_copy, ",");
        db_copy = NULL;
    }
 
    /* Trim whitespace */
    while (*db_name == ' ' || *db_name == '\t')
        db_name++;
 
    /* flawfinder: ignore - explicitly null-terminated on next line */
    strncpy(dbname, db_name, NAMEDATALEN - 1);
    dbname[NAMEDATALEN - 1] = '\0';
 
    /* Remove trailing whitespace */
    /* flawfinder: ignore - dbname was just null-terminated above */
    for (int i = strlen(dbname) - 1; i >= 0 && (dbname[i] == ' ' || dbname[i] == '\t'); i--)
        dbname[i] = '\0';
 
    pfree(db_list);
 
    /* Connect to the selected database */
    BackgroundWorkerInitializeConnection(dbname, NULL, 0);
 
    elog(LOG, "pgedge_vectorizer worker %d started (database: %s)",
         worker_id + 1, dbname);
 
    /* Set process display */
    pgstat_report_appname(psprintf("pgedge_vectorizer worker %d", worker_id + 1));
 
    /* Main work loop */
    while (!got_sigterm)
    {
        int rc;
        int wait_time;
 
        /* Reload configuration if SIGHUP received */
        if (got_sighup)
        {
            got_sighup = false;
            ProcessConfigFile(PGC_SIGHUP);
        }
 
        /* Update process status */
        pgstat_report_activity(STATE_IDLE, NULL);
 
        wait_time = pgedge_vectorizer_worker_poll_interval;
 
        /* Wait for work or timeout */
        rc = WaitLatch(MyLatch,
                       WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
                       wait_time,
                       PG_WAIT_EXTENSION);
 
        ResetLatch(MyLatch);
 
        /* Emergency bailout if postmaster has died */
        if (rc & WL_POSTMASTER_DEATH)
            proc_exit(1);
 
        /* Process pending queue items */
        pgstat_report_activity(STATE_RUNNING, "processing embedding queue");
 
        PG_TRY();
        {
            process_queue_batch(worker_id);
 
            /* Perform automatic cleanup if enabled */
            cleanup_completed_items(worker_id);
        }
        PG_CATCH();
        {
            EmitErrorReport();
            FlushErrorState();
 
            /* Don't exit on errors - log and continue */
            elog(LOG, "pgedge_vectorizer worker %d: error in processing, continuing",
                 worker_id + 1);
 
            /* Abort any transaction */
            AbortCurrentTransaction();
        }
        PG_END_TRY();
    }
 
    /* Cleanup before exit */
    elog(LOG, "pgedge_vectorizer worker %d shutting down", worker_id + 1);
    proc_exit(0);
}
 
/*
 * Process a batch of queue items
 */
static void
process_queue_batch(int worker_id)
{
    int ret;
    int batch_size = pgedge_vectorizer_batch_size;
    EmbeddingProvider *provider = NULL;
    char *error_msg = NULL;
 
    /* Start a transaction */
    SetCurrentStatementStartTimestamp();
    StartTransactionCommand();
    PushActiveSnapshot(GetTransactionSnapshot());
    SPI_connect();
 
    /* Fetch pending items using FOR UPDATE SKIP LOCKED */
    ret = SPI_execute(psprintf(
        "SELECT id, chunk_id, chunk_table, content, attempts, max_attempts "
        "FROM pgedge_vectorizer.queue "
        "WHERE status = 'pending' "
        "AND (next_retry_at IS NULL OR next_retry_at <= NOW()) "
        "ORDER BY attempts DESC, created_at "
        "LIMIT %d "
        "FOR UPDATE SKIP LOCKED",
        batch_size),
        false, batch_size);
 
    if (ret == SPI_OK_SELECT && SPI_processed > 0)
    {
        int n_items = SPI_processed;
        int64 *queue_ids = palloc(n_items * sizeof(int64));
        int64 *chunk_ids = palloc(n_items * sizeof(int64));
        char **chunk_tables = palloc(n_items * sizeof(char *));
        const char **contents = palloc(n_items * sizeof(char *));
        int *attempts = palloc(n_items * sizeof(int));
        int *max_attempts = palloc(n_items * sizeof(int));
        float **embeddings = NULL;
        int dim = 0;
        bool has_retries = false;
        int effective_batch_size = n_items;
 
        elog(DEBUG1, "Worker %d processing %d queue items", worker_id + 1, n_items);
 
        /* Extract data from result */
        for (int i = 0; i < n_items; i++)
        {
            bool isnull;
            Datum val;
 
            val = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull);
            queue_ids[i] = DatumGetInt64(val);
 
            val = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 2, &isnull);
            chunk_ids[i] = DatumGetInt64(val);
 
            val = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 3, &isnull);
            chunk_tables[i] = TextDatumGetCString(val);
 
            val = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 4, &isnull);
            contents[i] = TextDatumGetCString(val);
 
            val = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 5, &isnull);
            attempts[i] = DatumGetInt32(val);
 
            val = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 6, &isnull);
            max_attempts[i] = DatumGetInt32(val);
 
            if (attempts[i] > 0)
                has_retries = true;
        }
 
        /* If any items have been retried, process individually to isolate failures */
        if (has_retries && n_items > 1)
        {
            effective_batch_size = 1;
            elog(DEBUG1, "Worker %d: found retried items, processing individually", worker_id + 1);
        }
 
        /* Mark all as processing */
        for (int i = 0; i < n_items; i++)
        {
            SPI_execute(psprintf(
                "UPDATE pgedge_vectorizer.queue "
                "SET status = 'processing', processing_started_at = NOW() "
                "WHERE id = %ld",
                queue_ids[i]),
                false, 0);
        }
 
        /* Get the provider */
        provider = get_current_provider();
        if (provider == NULL)
        {
            elog(ERROR, "No provider configured");
        }
 
        /* Initialize provider if needed */
        if (!provider->init(&error_msg))
        {
            elog(ERROR, "Failed to initialize provider: %s",
                 error_msg ? error_msg : "unknown error");
        }
 
        /* Process items in batches of effective_batch_size */
        for (int batch_start = 0; batch_start < n_items; batch_start += effective_batch_size)
        {
            int batch_end;
            int batch_count;
 
            batch_end = batch_start + effective_batch_size;
            if (batch_end > n_items)
                batch_end = n_items;
            batch_count = batch_end - batch_start;
 
            /* Generate embeddings for this batch */
            embeddings = provider->generate_batch(&contents[batch_start], batch_count, &dim, &error_msg);
 
            if (embeddings != NULL)
            {
                /*
                 * Validate that the embedding dimension matches the chunk
                 * table's vector column. Check once per batch.
                 */
                {
                    int idx0 = batch_start;
                    int ret_dim;
                    bool isnull_dim;
                    Datum val_dim;
 
                    ret_dim = SPI_execute(psprintf(
                        "SELECT atttypmod FROM pg_attribute "
                        "WHERE attrelid = '%s'::regclass "
                        "AND attname = 'embedding'",
                        chunk_tables[idx0]),
                        true, 1);
 
                    if (ret_dim == SPI_OK_SELECT && SPI_processed == 1)
                    {
                        val_dim = SPI_getbinval(SPI_tuptable->vals[0],
                                                SPI_tuptable->tupdesc, 1, &isnull_dim);
                        if (!isnull_dim)
                        {
                            int table_dim = DatumGetInt32(val_dim);
                            if (table_dim > 0 && table_dim != dim)
                            {
                                elog(WARNING, "Embedding dimension mismatch for table %s: "
                                     "model returned %d dimensions but table expects %d. "
                                     "Reconfigure rudb_ai.model or recreate the "
                                     "chunk table with the correct dimension.",
                                     chunk_tables[idx0], dim, table_dim);
 
                                /* Fail all items in this batch */
                                for (int i = 0; i < batch_count; i++)
                                {
                                    int fidx = batch_start + i;
                                    SPI_execute(psprintf(
                                        "UPDATE pgedge_vectorizer.queue "
                                        "SET status = 'failed', "
                                        "    error_message = 'Dimension mismatch: model=%d, table=%d', "
                                        "    next_retry_at = NULL "
                                        "WHERE id = %ld",
                                        dim, table_dim, queue_ids[fidx]),
                                        false, 0);
                                }
 
                                /* Free embeddings and skip to next batch */
                                for (int i = 0; i < batch_count; i++)
                                {
                                    if (embeddings[i] != NULL)
                                        pfree(embeddings[i]);
                                }
                                pfree(embeddings);
                                embeddings = NULL;
                                continue;
                            }
                        }
                    }
                }
 
                /* Update chunk tables and mark as completed */
                for (int i = 0; i < batch_count; i++)
                {
                    int idx = batch_start + i;
                    PG_TRY();
                    {
                        update_embedding(chunk_ids[idx], chunk_tables[idx], embeddings[i], dim);
 
                        /* Mark as completed */
                        SPI_execute(psprintf(
                            "UPDATE pgedge_vectorizer.queue "
                            "SET status = 'completed', processed_at = NOW() "
                            "WHERE id = %ld",
                            queue_ids[idx]),
                            false, 0);
 
                        elog(DEBUG2, "Successfully processed queue item %ld", queue_ids[idx]);
                    }
                    PG_CATCH();
                    {
                        /* Check if retries remain */
                        if (attempts[idx] + 1 >= max_attempts[idx])
                        {
                            /* No retries left - mark as permanently failed */
                            SPI_execute(psprintf(
                                "UPDATE pgedge_vectorizer.queue "
                                "SET status = 'failed', "
                                "    attempts = attempts + 1, "
                                "    error_message = 'Failed to update embedding', "
                                "    next_retry_at = NULL "
                                "WHERE id = %ld",
                                queue_ids[idx]),
                                false, 0);
                        }
                        else
                        {
                            /* Retries remain - set back to pending with delay */
                            SPI_execute(psprintf(
                                "UPDATE pgedge_vectorizer.queue "
                                "SET status = 'pending', "
                                "    attempts = attempts + 1, "
                                "    error_message = 'Failed to update embedding', "
                                "    next_retry_at = NOW() + (attempts + 1) * INTERVAL '1 minute' "
                                "WHERE id = %ld",
                                queue_ids[idx]),
                                false, 0);
                        }
 
                        /* Re-throw */
                        PG_RE_THROW();
                    }
                    PG_END_TRY();
                }
 
                /* Free embeddings */
                for (int i = 0; i < batch_count; i++)
                {
                    if (embeddings[i] != NULL)
                        pfree(embeddings[i]);
                }
                pfree(embeddings);
            }
            else
            {
                /* Failed to generate embeddings - update status based on remaining retries */
                for (int i = 0; i < batch_count; i++)
                {
                    int idx = batch_start + i;
 
                    /* Check if retries remain */
                    if (attempts[idx] + 1 >= max_attempts[idx])
                    {
                        /* No retries left - mark as permanently failed */
                        SPI_execute(psprintf(
                            "UPDATE pgedge_vectorizer.queue "
                            "SET status = 'failed', "
                            "    attempts = attempts + 1, "
                            "    error_message = %s, "
                            "    next_retry_at = NULL "
                            "WHERE id = %ld",
                            error_msg ? psprintf("'%s'", error_msg) : "NULL",
                            queue_ids[idx]),
                            false, 0);
                    }
                    else
                    {
                        /* Retries remain - set back to pending with exponential backoff */
                        SPI_execute(psprintf(
                            "UPDATE pgedge_vectorizer.queue "
                            "SET status = 'pending', "
                            "    attempts = attempts + 1, "
                            "    error_message = %s, "
                            "    next_retry_at = NOW() + (attempts + 1) * INTERVAL '1 minute' "
                            "WHERE id = %ld",
                            error_msg ? psprintf("'%s'", error_msg) : "NULL",
                            queue_ids[idx]),
                            false, 0);
                    }
                }
 
                elog(WARNING, "Failed to generate embeddings for batch starting at %d: %s",
                     batch_start, error_msg ? error_msg : "unknown error");
            }
        }
 
        /* Cleanup */
        pfree(queue_ids);
        pfree(chunk_ids);
        pfree(chunk_tables);
        pfree(contents);
        pfree(attempts);
        pfree(max_attempts);
    }
 
    SPI_finish();
    PopActiveSnapshot();
    CommitTransactionCommand();
}
 
/*
 * Update a chunk table with the generated embedding
 */
static void
update_embedding(int64 chunk_id, const char *chunk_table, const float *embedding, int dim)
{
    StringInfoData vector_str;
    int ret;
 
    /* Build vector string: [0.1, 0.2, 0.3, ...] */
    initStringInfo(&vector_str);
    appendStringInfoChar(&vector_str, '[');
    for (int i = 0; i < dim; i++)
    {
        if (i > 0)
            appendStringInfoChar(&vector_str, ',');
        appendStringInfo(&vector_str, "%f", embedding[i]);
    }
    appendStringInfoChar(&vector_str, ']');
 
    /* Update the chunk table */
    ret = SPI_execute(psprintf(
        "UPDATE %s SET embedding = '%s'::vector WHERE id = %ld",
        chunk_table, vector_str.data, chunk_id),
        false, 0);
 
    if (ret != SPI_OK_UPDATE)
    {
        elog(ERROR, "Failed to update embedding in table %s for chunk %ld",
             chunk_table, chunk_id);
    }
 
    if (SPI_processed == 0)
    {
        elog(WARNING, "Chunk " INT64_FORMAT " not found in table %s "
             "(may have been deleted by a concurrent source update)",
             chunk_id, chunk_table);
    }
 
    pfree(vector_str.data);
}
 
/*
 * Clean up completed queue items older than auto_cleanup_hours
 */
static void
cleanup_completed_items(int worker_id)
{
    int ret;
    int rows_deleted = 0;
    time_t now;
 
    /* Skip if auto cleanup is disabled (set to 0) */
    if (pgedge_vectorizer_auto_cleanup_hours <= 0)
        return;
 
    /* Only perform cleanup once per hour (3600 seconds) */
    now = time(NULL);
    if (last_cleanup_time > 0 && (now - last_cleanup_time) < 3600)
        return;
 
    last_cleanup_time = now;
 
    StartTransactionCommand();
    PushActiveSnapshot(GetTransactionSnapshot());
 
    SPI_connect();
 
    /* Delete completed items older than configured hours */
    ret = SPI_execute(psprintf(
        "DELETE FROM pgedge_vectorizer.queue "
        "WHERE status = 'completed' "
        "AND processed_at < NOW() - INTERVAL '%d hours'",
        pgedge_vectorizer_auto_cleanup_hours),
        false, 0);
 
    if (ret == SPI_OK_DELETE)
    {
        rows_deleted = SPI_processed;
        if (rows_deleted > 0)
        {
            elog(LOG, "pgedge_vectorizer worker %d: cleaned up %d completed queue items older than %d hours",
                 worker_id + 1, rows_deleted, pgedge_vectorizer_auto_cleanup_hours);
        }
    }
 
    SPI_finish();
 
    PopActiveSnapshot();
    CommitTransactionCommand();
}