Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2026-10-06 6bac54b555d27f1a85c1e4f011a6e7bd9111b0d0
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
/*-------------------------------------------------------------------------
 *
 * hybrid_chunking.c
 *      Hybrid chunking implementation inspired by Docling's approach
 *
 * This implements a two-pass hybrid chunking strategy:
 * 1. Parse document structure (markdown) into hierarchical elements
 * 2. Apply tokenization-aware refinement:
 *    - Split oversized chunks that exceed token limits
 *    - Merge undersized consecutive chunks with same heading context
 *
 * Copyright (c) 2025 - 2026, pgEdge, Inc.
 *
 *-------------------------------------------------------------------------
 */
#include "pgedge_vectorizer.h"
#include "catalog/pg_type.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
 
/* Maximum heading levels in markdown (h1-h6) */
#define MAX_HEADING_LEVELS 6
 
/* Forward declarations */
static List *split_oversized_chunks(List *chunks, int max_tokens);
static List *merge_undersized_chunks(List *chunks, int min_tokens, int max_tokens);
static HybridChunk *create_hybrid_chunk(const char *content, const char *heading_context);
static void free_hybrid_chunk(HybridChunk *chunk);
static char *build_heading_context(char **heading_stack, int stack_depth);
static bool is_blank_line(const char *line, int len);
static int get_heading_level(const char *line, int len);
static bool is_code_fence(const char *line, int len);
static bool is_list_item(const char *line, int len);
static bool is_blockquote(const char *line, int len);
static bool is_horizontal_rule(const char *line, int len);
static bool is_table_row(const char *line, int len);
static bool is_likely_markdown(const char *content);
static ArrayType *elements_to_chunks_simple(List *elements, ChunkConfig *config);
 
/* Helper functions for markdown detection (reduces complexity of is_likely_markdown) */
static bool check_heading_indicator(const char *pos);
static bool check_code_fence_indicator(const char *pos);
static bool check_list_indicator(const char *pos);
static bool check_table_indicator(const char *pos, const char *line_end);
static bool check_link_indicator(const char *pos);
 
/* Helper for creating markdown elements (reduces duplication in parse_markdown_structure) */
static MarkdownElement *create_markdown_element(MarkdownElementType type, int heading_level,
                                                const char *content, int content_len,
                                                const char *heading_context);
 
/*
 * Check for heading indicator at position (# followed by space)
 */
static bool
check_heading_indicator(const char *pos)
{
    int level = 0;
 
    while (level < MAX_HEADING_LEVELS && pos[level] == '#')
        level++;
 
    if (level > 0 && (pos[level] == ' ' || pos[level] == '\t' ||
                      pos[level] == '\n' || pos[level] == '\0'))
        return true;
 
    return false;
}
 
/*
 * Check for code fence indicator at position (``` or ~~~)
 */
static bool
check_code_fence_indicator(const char *pos)
{
    if ((*pos == '`' || *pos == '~') &&
        pos[1] != '\0' && pos[2] != '\0' &&
        pos[0] == pos[1] && pos[1] == pos[2])
        return true;
 
    return false;
}
 
/*
 * Check for list indicator at position (-, *, +, or numbered)
 */
static bool
check_list_indicator(const char *pos)
{
    /* Unordered list: -, *, + followed by space */
    if ((*pos == '-' || *pos == '*' || *pos == '+') &&
        pos[1] != '\0' && (pos[1] == ' ' || pos[1] == '\t'))
        return true;
 
    /* Ordered list: digit(s) followed by . or ) and space */
    if (*pos >= '0' && *pos <= '9')
    {
        const char *p = pos;
 
        while (*p >= '0' && *p <= '9')
            p++;
 
        if ((*p == '.' || *p == ')') &&
            p[1] != '\0' && (p[1] == ' ' || p[1] == '\t'))
            return true;
    }
 
    return false;
}
 
/*
 * Check for table indicator (| character with another | on same line)
 */
static bool
check_table_indicator(const char *pos, const char *line_end)
{
    const char *p = pos + 1;
 
    while (p < line_end && *p != '\0' && *p != '\n')
    {
        if (*p == '|')
            return true;
        p++;
    }
 
    return false;
}
 
/*
 * Check for link indicator [text](url) or ![alt](url)
 */
static bool
check_link_indicator(const char *pos)
{
    const char *p = pos + 1;
    int bracket_depth = 1;
 
    while (*p != '\0' && bracket_depth > 0)
    {
        if (*p == '[')
            bracket_depth++;
        else if (*p == ']')
            bracket_depth--;
        p++;
    }
 
    if (bracket_depth == 0 && *p == '(')
        return true;
 
    return false;
}
 
/*
 * Create a markdown element with the given properties
 */
static MarkdownElement *
create_markdown_element(MarkdownElementType type, int heading_level,
                        const char *content, int content_len,
                        const char *heading_context)
{
    MarkdownElement *elem = palloc0(sizeof(MarkdownElement));
 
    elem->type = type;
    elem->heading_level = heading_level;
 
    if (content_len > 0)
        elem->content = pnstrdup(content, content_len);
    else
        elem->content = pstrdup(content);
 
    elem->token_count = count_tokens(elem->content, pgedge_vectorizer_model);
    elem->heading_context = heading_context ? pstrdup(heading_context) : NULL;
 
    return elem;
}
 
/*
 * Detect if content is likely to be markdown
 *
 * Returns true if the content contains markdown-specific syntax that
 * would benefit from structure-aware chunking. Falls back to token-based
 * chunking for plain text to avoid unnecessary overhead.
 *
 * Detection criteria (need at least 2 indicators for confidence):
 * - Headings (# at start of line)
 * - Code fences (``` or ~~~)
 * - List items (-, *, +, or numbered)
 * - Blockquotes (>)
 * - Tables (| characters)
 * - Links/images ([text](url) or ![alt](url))
 */
static bool
is_likely_markdown(const char *content)
{
    int indicators = 0;
    const char *pos = content;
    const char *line_end;
    bool has_heading = false;
    bool has_code_fence = false;
 
    if (content == NULL || content[0] == '\0')
        return false;
 
    /* Scan content line by line */
    while (*pos != '\0')
    {
        /* Find end of current line */
        line_end = pos;
        while (*line_end != '\0' && *line_end != '\n')
            line_end++;
 
        /* Skip leading whitespace (up to 3 spaces for markdown) */
        while (*pos == ' ' && pos < line_end && (pos - content) < 4)
            pos++;
 
        /* Check line-start patterns */
        if (*pos == '#' && !has_heading && check_heading_indicator(pos))
        {
            has_heading = true;
            indicators++;
        }
 
        if ((*pos == '`' || *pos == '~') && !has_code_fence && check_code_fence_indicator(pos))
        {
            has_code_fence = true;
            indicators++;
        }
 
        if (check_list_indicator(pos))
            indicators++;
 
        if (*pos == '>')
            indicators++;
 
        /* Check inline patterns within the line */
        for (const char *p = pos; p < line_end; p++)
        {
            if (*p == '|' && check_table_indicator(p, line_end))
            {
                indicators++;
                break;  /* Only count once per line */
            }
 
            if (*p == '[' && check_link_indicator(p))
            {
                indicators++;
                break;  /* Only count once per line */
            }
        }
 
        /* Early exit if we have enough indicators */
        if (indicators >= 2)
            return true;
 
        /* Move to next line */
        pos = (*line_end == '\n') ? line_end + 1 : line_end;
    }
 
    /* Require at least 1 strong indicator (heading or code fence) or 2 weak indicators */
    return (has_heading || has_code_fence || indicators >= 2);
}
 
/*
 * Parse markdown content into structured elements
 *
 * This function identifies markdown structural elements:
 * - Headings (# through ######)
 * - Code blocks (``` ... ```)
 * - List items (-, *, 1.)
 * - Blockquotes (>)
 * - Tables (| ... |)
 * - Paragraphs (default text blocks)
 */
List *
parse_markdown_structure(const char *content)
{
    List *elements = NIL;
    const char *pos = content;
    const char *line_start;
    int line_len;
    bool in_code_block = false;
    StringInfoData current_block;
    MarkdownElementType current_type = MD_ELEMENT_PARAGRAPH;
    char *heading_stack[MAX_HEADING_LEVELS] = {NULL};
    char *current_heading_context = NULL;
 
    if (content == NULL || content[0] == '\0')
        return NIL;
 
    initStringInfo(&current_block);
 
    while (*pos != '\0')
    {
        int heading_level;
 
        /* Find end of current line */
        line_start = pos;
        while (*pos != '\0' && *pos != '\n')
            pos++;
        line_len = pos - line_start;
 
        /* Handle code block toggle */
        if (is_code_fence(line_start, line_len))
        {
            if (in_code_block)
            {
                /* End code block - save accumulated content */
                appendBinaryStringInfo(&current_block, line_start, line_len);
                if (*pos == '\n')
                {
                    appendStringInfoChar(&current_block, '\n');
                    pos++;
                }
 
                if (current_block.len > 0)
                elements = lappend(elements,
                    create_markdown_element(MD_ELEMENT_CODE_BLOCK, 0,
                        current_block.data, 0, current_heading_context));
 
                resetStringInfo(&current_block);
                in_code_block = false;
                current_type = MD_ELEMENT_PARAGRAPH;
                continue;
            }
            else
            {
                /* Start code block - save any pending content first */
                if (current_block.len > 0)
                {
                    elements = lappend(elements,
                        create_markdown_element(current_type, 0,
                            current_block.data, 0, current_heading_context));
                    resetStringInfo(&current_block);
                }
 
                in_code_block = true;
                current_type = MD_ELEMENT_CODE_BLOCK;
            }
        }
 
        /* If in code block, just accumulate */
        if (in_code_block)
        {
            appendBinaryStringInfo(&current_block, line_start, line_len);
            if (*pos == '\n')
            {
                appendStringInfoChar(&current_block, '\n');
                pos++;
            }
            continue;
        }
 
        /* Check for blank line - paragraph separator */
        if (is_blank_line(line_start, line_len))
        {
            if (current_block.len > 0)
            {
                elements = lappend(elements,
                    create_markdown_element(current_type, 0,
                        current_block.data, 0, current_heading_context));
                resetStringInfo(&current_block);
            }
            current_type = MD_ELEMENT_PARAGRAPH;
            if (*pos == '\n')
                pos++;
            continue;
        }
 
        /* Check for heading */
        heading_level = get_heading_level(line_start, line_len);
        if (heading_level > 0)
        {
            const char *heading_text;
            int heading_text_len;
            int i;
 
            /* Save any pending content */
            if (current_block.len > 0)
            {
                elements = lappend(elements,
                    create_markdown_element(current_type, 0,
                        current_block.data, 0, current_heading_context));
                resetStringInfo(&current_block);
            }
 
            /* Update heading stack - clear deeper levels */
            for (i = heading_level; i < MAX_HEADING_LEVELS; i++)
            {
                if (heading_stack[i] != NULL)
                {
                    pfree(heading_stack[i]);
                    heading_stack[i] = NULL;
                }
            }
 
            /* Extract heading text (skip # symbols and space) */
            heading_text = line_start + heading_level;
            while (*heading_text == ' ' || *heading_text == '\t')
                heading_text++;
            heading_text_len = line_len - (heading_text - line_start);
 
            /* Store in heading stack */
            if (heading_stack[heading_level - 1] != NULL)
                pfree(heading_stack[heading_level - 1]);
            heading_stack[heading_level - 1] = pnstrdup(heading_text, heading_text_len);
 
            /* Update current heading context */
            if (current_heading_context != NULL)
                pfree(current_heading_context);
            current_heading_context = build_heading_context(heading_stack, MAX_HEADING_LEVELS);
 
            /* Create heading element */
            elements = lappend(elements,
                create_markdown_element(MD_ELEMENT_HEADING, heading_level,
                    line_start, line_len, current_heading_context));
 
            current_type = MD_ELEMENT_PARAGRAPH;
            if (*pos == '\n')
                pos++;
            continue;
        }
 
        /* Check for horizontal rule */
        if (is_horizontal_rule(line_start, line_len))
        {
            if (current_block.len > 0)
            {
                elements = lappend(elements,
                    create_markdown_element(current_type, 0,
                        current_block.data, 0, current_heading_context));
                resetStringInfo(&current_block);
            }
 
            elements = lappend(elements,
                create_markdown_element(MD_ELEMENT_HORIZONTAL_RULE, 0,
                    line_start, line_len, current_heading_context));
 
            current_type = MD_ELEMENT_PARAGRAPH;
            if (*pos == '\n')
                pos++;
            continue;
        }
 
        /* Check for list item */
        if (is_list_item(line_start, line_len))
        {
            /* If switching from non-list, save pending content */
            if (current_type != MD_ELEMENT_LIST_ITEM && current_block.len > 0)
            {
                elements = lappend(elements,
                    create_markdown_element(current_type, 0,
                        current_block.data, 0, current_heading_context));
                resetStringInfo(&current_block);
            }
 
            current_type = MD_ELEMENT_LIST_ITEM;
        }
 
        /* Check for blockquote */
        if (is_blockquote(line_start, line_len))
        {
            if (current_type != MD_ELEMENT_BLOCKQUOTE && current_block.len > 0)
            {
                elements = lappend(elements,
                    create_markdown_element(current_type, 0,
                        current_block.data, 0, current_heading_context));
                resetStringInfo(&current_block);
            }
 
            current_type = MD_ELEMENT_BLOCKQUOTE;
        }
 
        /* Check for table */
        if (is_table_row(line_start, line_len))
        {
            if (current_type != MD_ELEMENT_TABLE && current_block.len > 0)
            {
                elements = lappend(elements,
                    create_markdown_element(current_type, 0,
                        current_block.data, 0, current_heading_context));
                resetStringInfo(&current_block);
            }
 
            current_type = MD_ELEMENT_TABLE;
        }
 
        /* Accumulate line to current block */
        if (current_block.len > 0)
            appendStringInfoChar(&current_block, '\n');
        appendBinaryStringInfo(&current_block, line_start, line_len);
 
        if (*pos == '\n')
            pos++;
    }
 
    /* Save final block */
    if (current_block.len > 0)
        elements = lappend(elements,
            create_markdown_element(current_type, 0,
                current_block.data, 0, current_heading_context));
 
    /* Cleanup */
    pfree(current_block.data);
    for (int i = 0; i < MAX_HEADING_LEVELS; i++)
    {
        if (heading_stack[i] != NULL)
            pfree(heading_stack[i]);
    }
    if (current_heading_context != NULL)
        pfree(current_heading_context);
 
    return elements;
}
 
/*
 * Free list of markdown elements
 */
void
free_markdown_elements(List *elements)
{
    ListCell *lc;
 
    foreach(lc, elements)
    {
        MarkdownElement *elem = (MarkdownElement *) lfirst(lc);
        if (elem->content)
            pfree(elem->content);
        if (elem->heading_context)
            pfree(elem->heading_context);
        pfree(elem);
    }
    list_free(elements);
}
 
/*
 * Build heading context string from heading stack
 * Format: "# H1 > ## H2 > ### H3"
 */
static char *
build_heading_context(char **heading_stack, int stack_size)
{
    StringInfoData result;
    bool first = true;
 
    initStringInfo(&result);
 
    for (int i = 0; i < stack_size; i++)
    {
        if (heading_stack[i] != NULL)
        {
            if (!first)
                appendStringInfoString(&result, " > ");
            first = false;
 
            /* Add heading level markers */
            for (int j = 0; j <= i; j++)
                appendStringInfoChar(&result, '#');
            appendStringInfoChar(&result, ' ');
            appendStringInfoString(&result, heading_stack[i]);
        }
    }
 
    if (result.len == 0)
    {
        pfree(result.data);
        return NULL;
    }
 
    return result.data;
}
 
/*
 * Create a hybrid chunk with content and heading context
 */
static HybridChunk *
create_hybrid_chunk(const char *content, const char *heading_context)
{
    HybridChunk *chunk = palloc0(sizeof(HybridChunk));
    chunk->content = pstrdup(content);
    chunk->token_count = count_tokens(content, pgedge_vectorizer_model);
    chunk->heading_context = heading_context ? pstrdup(heading_context) : NULL;
    chunk->chunk_index = 0;
    return chunk;
}
 
/*
 * Free a hybrid chunk
 */
static void
free_hybrid_chunk(HybridChunk *chunk)
{
    if (chunk->content)
        pfree(chunk->content);
    if (chunk->heading_context)
        pfree(chunk->heading_context);
    pfree(chunk);
}
 
/*
 * Check if line is blank (empty or whitespace only)
 */
static bool
is_blank_line(const char *line, int len)
{
    for (int i = 0; i < len; i++)
    {
        if (line[i] != ' ' && line[i] != '\t' && line[i] != '\r')
            return false;
    }
    return true;
}
 
/*
 * Get heading level (1-6) from line, or 0 if not a heading
 */
static int
get_heading_level(const char *line, int len)
{
    int level = 0;
 
    if (len == 0)
        return 0;
 
    /* Count # at start */
    while (level < len && level < MAX_HEADING_LEVELS && line[level] == '#')
        level++;
 
    /* Must have at least one # and be followed by space or end of line */
    if (level == 0)
        return 0;
    if (level < len && line[level] != ' ' && line[level] != '\t')
        return 0;
 
    return level;
}
 
/*
 * Check if line is a code fence (``` or ~~~)
 */
static bool
is_code_fence(const char *line, int len)
{
    int i = 0;
 
    /* Skip leading whitespace (up to 3 spaces) */
    while (i < len && i < 3 && line[i] == ' ')
        i++;
 
    if (len - i < 3)
        return false;
 
    /* Check for ``` or ~~~ */
    if ((line[i] == '`' && line[i+1] == '`' && line[i+2] == '`') ||
        (line[i] == '~' && line[i+1] == '~' && line[i+2] == '~'))
        return true;
 
    return false;
}
 
/*
 * Check if line is a list item
 */
static bool
is_list_item(const char *line, int len)
{
    int i = 0;
 
    /* Skip leading whitespace */
    while (i < len && (line[i] == ' ' || line[i] == '\t'))
        i++;
 
    if (i >= len)
        return false;
 
    /* Check for unordered list markers: -, *, + followed by space/tab */
    if ((line[i] == '-' || line[i] == '*' || line[i] == '+'))
    {
        if (i + 1 < len && (line[i+1] == ' ' || line[i+1] == '\t'))
            return true;
        return false;
    }
 
    /* Check for ordered list: digit(s) followed by . or ) and space/tab */
    if (line[i] >= '0' && line[i] <= '9')
    {
        while (i < len && line[i] >= '0' && line[i] <= '9')
            i++;
        if (i < len && (line[i] == '.' || line[i] == ')'))
        {
            if (i + 1 < len && (line[i+1] == ' ' || line[i+1] == '\t'))
                return true;
        }
    }
 
    return false;
}
 
/*
 * Check if line is a blockquote
 */
static bool
is_blockquote(const char *line, int len)
{
    int i = 0;
 
    /* Skip leading whitespace (up to 3 spaces) */
    while (i < len && i < 3 && line[i] == ' ')
        i++;
 
    if (i < len && line[i] == '>')
        return true;
 
    return false;
}
 
/*
 * Check if line is a horizontal rule (---, ***, ___)
 */
static bool
is_horizontal_rule(const char *line, int len)
{
    int i = 0;
    char rule_char = '\0';
    int count = 0;
 
    /* Skip leading whitespace (up to 3 spaces) */
    while (i < len && i < 3 && line[i] == ' ')
        i++;
 
    if (i >= len)
        return false;
 
    /* Must start with -, *, or _ */
    if (line[i] != '-' && line[i] != '*' && line[i] != '_')
        return false;
 
    rule_char = line[i];
 
    /* Count rule characters (allowing spaces between) */
    while (i < len)
    {
        if (line[i] == rule_char)
            count++;
        else if (line[i] != ' ')
            return false;
        i++;
    }
 
    /* Must have at least 3 rule characters */
    return count >= 3;
}
 
/*
 * Check if line is a table row
 */
static bool
is_table_row(const char *line, int len)
{
    bool has_pipe = false;
 
    for (int i = 0; i < len; i++)
    {
        if (line[i] == '|')
            has_pipe = true;
    }
 
    /* Simple heuristic: line contains | character */
    return has_pipe;
}
 
/*
 * Split chunks that exceed the token limit
 *
 * Pass 1 of hybrid refinement: Split oversized chunks
 */
static List *
split_oversized_chunks(List *chunks, int max_tokens)
{
    List *result = NIL;
    ListCell *lc;
 
    foreach(lc, chunks)
    {
        HybridChunk *chunk = (HybridChunk *) lfirst(lc);
 
        if (chunk->token_count <= max_tokens)
        {
            /* Chunk is within limits, keep as is */
            result = lappend(result, chunk);
        }
        else
        {
            /* Split oversized chunk */
            const char *content = chunk->content;
            /* flawfinder: ignore - chunk->content is palloc'd, null-terminated */
            int content_len = strlen(content);
            int start_offset = 0;
 
            while (start_offset < content_len)
            {
                int target_offset;
                int end_offset;
                char *sub_content;
                HybridChunk *sub_chunk;
 
                /* Find target end position based on token count */
                target_offset = get_char_offset_for_tokens(
                    content + start_offset,
                    max_tokens,
                    pgedge_vectorizer_model
                );
 
                /* Find good break point */
                end_offset = find_good_break_point(
                    content + start_offset,
                    target_offset,
                    content_len - start_offset
                );
 
                /* Ensure progress */
                if (end_offset <= 0)
                    end_offset = target_offset > 0 ? target_offset : content_len - start_offset;
 
                /* Extract sub-chunk */
                sub_content = pnstrdup(content + start_offset, end_offset);
                sub_chunk = create_hybrid_chunk(sub_content, chunk->heading_context);
                pfree(sub_content);
 
                result = lappend(result, sub_chunk);
 
                /* Move to next portion */
                start_offset += end_offset;
 
                /* Skip whitespace */
                while (start_offset < content_len &&
                       (content[start_offset] == ' ' ||
                        content[start_offset] == '\t' ||
                        content[start_offset] == '\n' ||
                        content[start_offset] == '\r'))
                {
                    start_offset++;
                }
            }
 
            /* Free original oversized chunk */
            free_hybrid_chunk(chunk);
        }
    }
 
    return result;
}
 
/*
 * Merge consecutive undersized chunks with same heading context
 *
 * Pass 2 of hybrid refinement: Merge undersized chunks
 */
static List *
merge_undersized_chunks(List *chunks, int min_tokens, int max_tokens)
{
    List *result = NIL;
    ListCell *lc;
    HybridChunk *pending = NULL;
 
    foreach(lc, chunks)
    {
        HybridChunk *chunk = (HybridChunk *) lfirst(lc);
 
        if (pending == NULL)
        {
            /* First chunk or after flush */
            if (chunk->token_count >= min_tokens)
            {
                /* Chunk is large enough, output directly */
                result = lappend(result, chunk);
            }
            else
            {
                /* Undersized, start accumulating */
                pending = chunk;
            }
        }
        else
        {
            /* We have a pending undersized chunk */
            bool same_context = false;
 
            /* Check if contexts match (both NULL or equal strings) */
            if (pending->heading_context == NULL && chunk->heading_context == NULL)
                same_context = true;
            else if (pending->heading_context != NULL && chunk->heading_context != NULL &&
                     strcmp(pending->heading_context, chunk->heading_context) == 0)
                same_context = true;
 
            /* Check if we can merge */
            if (same_context && pending->token_count + chunk->token_count <= max_tokens)
            {
                /* Merge chunks */
                StringInfoData merged;
                initStringInfo(&merged);
                appendStringInfoString(&merged, pending->content);
                appendStringInfoString(&merged, "\n\n");
                appendStringInfoString(&merged, chunk->content);
 
                /* Update pending chunk */
                pfree(pending->content);
                pending->content = merged.data;
                pending->token_count = count_tokens(pending->content, pgedge_vectorizer_model);
 
                /* Free merged chunk */
                free_hybrid_chunk(chunk);
            }
            else
            {
                /* Cannot merge - flush pending and set new pending/output */
                result = lappend(result, pending);
 
                if (chunk->token_count >= min_tokens)
                {
                    result = lappend(result, chunk);
                    pending = NULL;
                }
                else
                {
                    pending = chunk;
                }
            }
        }
    }
 
    /* Flush any remaining pending chunk */
    if (pending != NULL)
        result = lappend(result, pending);
 
    return result;
}
 
/*
 * Convert parsed markdown elements to simple chunks (no refinement)
 *
 * Used by the pure 'markdown' strategy - respects structure but doesn't
 * do the split/merge refinement passes.
 */
static ArrayType *
elements_to_chunks_simple(List *elements, ChunkConfig *config)
{
    ListCell *lc;
    int chunk_count;
    Datum *chunk_datums;
    ArrayType *result;
    int i;
    List *chunks = NIL;
 
    if (elements == NIL)
        return construct_empty_array(TEXTOID);
 
    /* Convert elements to chunks, respecting structure boundaries */
    foreach(lc, elements)
    {
        MarkdownElement *elem = (MarkdownElement *) lfirst(lc);
 
        /* Skip horizontal rules */
        if (elem->type == MD_ELEMENT_HORIZONTAL_RULE)
            continue;
 
        /* If element exceeds chunk size, we need to split it */
        if (elem->token_count > config->chunk_size)
        {
            /* Split large elements at natural boundaries */
            const char *content = elem->content;
            /* flawfinder: ignore - elem->content is palloc'd, null-terminated */
            int content_len = strlen(content);
            int start_offset = 0;
 
            while (start_offset < content_len)
            {
                int target_offset;
                int end_offset;
                char *sub_content;
                HybridChunk *chunk;
 
                target_offset = get_char_offset_for_tokens(
                    content + start_offset,
                    config->chunk_size,
                    pgedge_vectorizer_model
                );
 
                end_offset = find_good_break_point(
                    content + start_offset,
                    target_offset,
                    content_len - start_offset
                );
 
                if (end_offset <= 0)
                    end_offset = target_offset > 0 ? target_offset : content_len - start_offset;
 
                sub_content = pnstrdup(content + start_offset, end_offset);
                chunk = create_hybrid_chunk(sub_content, elem->heading_context);
                pfree(sub_content);
 
                chunks = lappend(chunks, chunk);
 
                start_offset += end_offset;
                while (start_offset < content_len &&
                       (content[start_offset] == ' ' ||
                        content[start_offset] == '\t' ||
                        content[start_offset] == '\n'))
                {
                    start_offset++;
                }
            }
        }
        else
        {
            /* Element fits in one chunk */
            HybridChunk *chunk = create_hybrid_chunk(elem->content, elem->heading_context);
            chunks = lappend(chunks, chunk);
        }
    }
 
    /* Convert to array */
    chunk_count = list_length(chunks);
    if (chunk_count == 0)
        return construct_empty_array(TEXTOID);
 
    chunk_datums = palloc(chunk_count * sizeof(Datum));
 
    i = 0;
    foreach(lc, chunks)
    {
        HybridChunk *chunk = (HybridChunk *) lfirst(lc);
        StringInfoData chunk_text;
 
        initStringInfo(&chunk_text);
 
        /* flawfinder: ignore - heading_context is palloc'd, null-terminated */
        if (chunk->heading_context != NULL && strlen(chunk->heading_context) > 0)
        {
            appendStringInfoString(&chunk_text, "[Context: ");
            appendStringInfoString(&chunk_text, chunk->heading_context);
            appendStringInfoString(&chunk_text, "]\n\n");
        }
 
        appendStringInfoString(&chunk_text, chunk->content);
 
        chunk_datums[i++] = PointerGetDatum(cstring_to_text(chunk_text.data));
        pfree(chunk_text.data);
    }
 
    result = construct_array(chunk_datums, chunk_count, TEXTOID, -1, false, TYPALIGN_INT);
 
    /* Cleanup */
    pfree(chunk_datums);
    foreach(lc, chunks)
    {
        free_hybrid_chunk((HybridChunk *) lfirst(lc));
    }
    list_free(chunks);
 
    return result;
}
 
/*
 * Pure markdown chunking (structure-aware, no refinement)
 *
 * Respects markdown structure boundaries but doesn't apply the
 * split/merge refinement passes. Simpler and faster than hybrid,
 * but may produce less optimal chunk sizes for embeddings.
 *
 * Falls back to token-based chunking if content isn't markdown.
 */
ArrayType *
chunk_markdown(const char *content, ChunkConfig *config)
{
    List *elements;
    ArrayType *result;
 
    if (content == NULL || content[0] == '\0')
        return construct_empty_array(TEXTOID);
 
    /* Check if content is actually markdown */
    if (!is_likely_markdown(content))
    {
        elog(DEBUG1, "Content doesn't appear to be markdown, falling back to token-based chunking");
        return chunk_by_tokens(content, config);
    }
 
    elog(DEBUG1, "Markdown chunking: chunk_size=%d", config->chunk_size);
 
    /* Parse structure */
    elements = parse_markdown_structure(content);
 
    if (elements == NIL)
        return construct_empty_array(TEXTOID);
 
    elog(DEBUG2, "Parsed %d markdown elements", list_length(elements));
 
    /* Convert to chunks (simple, no refinement) */
    result = elements_to_chunks_simple(elements, config);
 
    /* Cleanup */
    free_markdown_elements(elements);
 
    return result;
}
 
/*
 * Main hybrid chunking function
 *
 * Implements Docling-style hybrid chunking:
 * 1. Detect if content is markdown (fall back to token-based if not)
 * 2. Parse markdown structure into elements
 * 3. Convert elements to initial chunks with heading context
 * 4. Split oversized chunks (Pass 1)
 * 5. Merge undersized consecutive chunks with same context (Pass 2)
 * 6. Return as PostgreSQL text array
 */
ArrayType *
chunk_hybrid(const char *content, ChunkConfig *config)
{
    List *elements;
    List *chunks = NIL;
    List *refined_chunks;
    ListCell *lc;
    int chunk_count;
    Datum *chunk_datums;
    ArrayType *result;
    int i;
    int min_tokens;
 
    if (content == NULL || content[0] == '\0')
        return construct_empty_array(TEXTOID);
 
    /* Step 0: Check if content is actually markdown */
    if (!is_likely_markdown(content))
    {
        elog(DEBUG1, "Content doesn't appear to be markdown, falling back to token-based chunking");
        return chunk_by_tokens(content, config);
    }
 
    elog(DEBUG1, "Hybrid chunking: chunk_size=%d, overlap=%d",
         config->chunk_size, config->overlap);
 
    /* Step 1: Parse markdown structure */
    elements = parse_markdown_structure(content);
 
    if (elements == NIL)
        return construct_empty_array(TEXTOID);
 
    elog(DEBUG2, "Parsed %d markdown elements", list_length(elements));
 
    /* Step 2: Convert elements to initial chunks with heading context */
    foreach(lc, elements)
    {
        MarkdownElement *elem = (MarkdownElement *) lfirst(lc);
        HybridChunk *chunk;
 
        /* Skip horizontal rules - they don't add content value */
        if (elem->type == MD_ELEMENT_HORIZONTAL_RULE)
            continue;
 
        chunk = create_hybrid_chunk(elem->content, elem->heading_context);
        chunks = lappend(chunks, chunk);
    }
 
    /* Free elements (we've copied the content) */
    free_markdown_elements(elements);
 
    if (chunks == NIL)
        return construct_empty_array(TEXTOID);
 
    elog(DEBUG2, "Created %d initial chunks", list_length(chunks));
 
    /* Step 3: Split oversized chunks (Pass 1) */
    refined_chunks = split_oversized_chunks(chunks, config->chunk_size);
    list_free(chunks);  /* List structure only, chunks moved to refined_chunks */
 
    elog(DEBUG2, "After split pass: %d chunks", list_length(refined_chunks));
 
    /* Step 4: Merge undersized chunks (Pass 2) */
    /* Use 25% of chunk_size as minimum threshold for merging */
    min_tokens = config->chunk_size / 4;
    if (min_tokens < 20)
        min_tokens = 20;
 
    chunks = merge_undersized_chunks(refined_chunks, min_tokens, config->chunk_size);
    list_free(refined_chunks);  /* List structure only */
 
    elog(DEBUG2, "After merge pass: %d chunks", list_length(chunks));
 
    /* Step 5: Convert to PostgreSQL text array */
    chunk_count = list_length(chunks);
    if (chunk_count == 0)
        return construct_empty_array(TEXTOID);
 
    chunk_datums = palloc(chunk_count * sizeof(Datum));
 
    i = 0;
    foreach(lc, chunks)
    {
        HybridChunk *chunk = (HybridChunk *) lfirst(lc);
        StringInfoData chunk_text;
 
        initStringInfo(&chunk_text);
 
        /* Optionally prepend heading context for better retrieval */
        /* flawfinder: ignore - heading_context is palloc'd, null-terminated */
        if (chunk->heading_context != NULL && strlen(chunk->heading_context) > 0)
        {
            appendStringInfoString(&chunk_text, "[Context: ");
            appendStringInfoString(&chunk_text, chunk->heading_context);
            appendStringInfoString(&chunk_text, "]\n\n");
        }
 
        appendStringInfoString(&chunk_text, chunk->content);
 
        chunk_datums[i++] = PointerGetDatum(cstring_to_text(chunk_text.data));
        pfree(chunk_text.data);
    }
 
    result = construct_array(chunk_datums, chunk_count, TEXTOID, -1, false, TYPALIGN_INT);
 
    /* Cleanup */
    pfree(chunk_datums);
    foreach(lc, chunks)
    {
        free_hybrid_chunk((HybridChunk *) lfirst(lc));
    }
    list_free(chunks);
 
    elog(DEBUG1, "Hybrid chunking produced %d chunks", chunk_count);
 
    return result;
}