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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::kvp::KvpPrefixSampler;
pub use crate::types::{RecordId, Sentence, SourceId, TaxonomyValue};
/// Trust/quality metadata for a record.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct QualityScore {
/// Normalized 0-1 trust measure combining provenance, recency, and manual reviews.
pub trust: f32,
}
impl Default for QualityScore {
fn default() -> Self {
Self {
// Assume medium trust by default, allowing recipes to upweight or downweight based on other signals.
trust: 0.5,
}
}
}
/// Canonical record payload produced by a DataSource.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DataRecord {
/// Stable record identifier (used for splits and determinism).
pub id: RecordId,
/// Source identifier that produced this record.
pub source: SourceId,
/// Canonical creation time for the record (used for ordering/metadata).
pub created_at: DateTime<Utc>,
/// Last update time for the record (used for refresh decisions).
pub updated_at: DateTime<Utc>,
/// Trust/quality score used to weight sampling.
pub quality: QualityScore,
/// Free-form tags (e.g., source id, year, date) used for filtering/recipes.
pub taxonomy: Vec<TaxonomyValue>,
/// Structured content sections used by sampling recipes.
pub sections: Vec<RecordSection>,
/// Optional metadata prefix policy for KVP sampling (key-value headers injected into text).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub meta_prefix: Option<KvpPrefixSampler>,
}
/// A structured section within a record.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RecordSection {
/// Semantic role used by selectors (for example, anchor vs context text).
pub role: SectionRole,
/// Optional short heading/title for this section.
pub heading: Option<String>,
/// Full section text.
pub text: String,
/// Sentence-level segmentation of `text` used by chunking strategies.
pub sentences: Vec<Sentence>,
}
/// Role label for a section.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum SectionRole {
/// Primary section typically used as an anchor candidate.
Anchor,
/// Supporting/context section used for positives, negatives, or text samples.
Context,
}
/// A chunked view over a section.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RecordChunk {
/// Parent record id this chunk belongs to.
pub record_id: RecordId,
/// Index of the source section in `DataRecord.sections`.
pub section_idx: usize,
/// Chunk view metadata (window position or summary fallback).
pub view: ChunkView,
/// Rendered chunk text (possibly with metadata prefix decoration).
pub text: String,
/// Approximate token count for scheduling/weighting heuristics.
pub tokens_estimate: usize,
/// Trust/quality inherited from the parent record.
pub quality: QualityScore,
}
/// Chunk view metadata (window or summary).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ChunkView {
/// Sliding-window chunk extracted directly from section text.
Window {
/// Zero-based window index within the section.
index: usize,
/// Overlap (in tokens) with the previous window.
overlap: usize,
/// Nominal window span in tokens.
span: usize,
},
/// Summary fallback chunk used when window extraction is unavailable.
SummaryFallback {
/// Name of summary strategy that produced this fallback chunk.
strategy: String,
/// Precomputed base weight for summary-fallback chunks before trust/floor are applied.
weight: f32,
},
}
/// Sample pair (positive/negative) derived from a triplet.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SamplePair {
/// Recipe name used to generate this pair.
pub recipe: String,
/// Anchor chunk used to build this supervised pair.
pub anchor: RecordChunk,
/// Candidate chunk paired with the anchor.
pub positive: RecordChunk,
/// Training weight for this pair.
pub weight: f32,
/// Optional instruction/prompt hint for this sample.
pub instruction: Option<String>,
/// Supervision label (positive or negative).
pub label: PairLabel,
/// Optional reason/annotation describing the label.
pub reason: Option<String>,
}
/// Sample triplet (anchor/positive/negative).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SampleTriplet {
/// Recipe name used to generate this triplet.
pub recipe: String,
/// Anchor chunk.
pub anchor: RecordChunk,
/// Positive chunk.
pub positive: RecordChunk,
/// Negative chunk.
pub negative: RecordChunk,
/// Training weight for this triplet.
pub weight: f32,
/// Optional instruction/prompt hint for this sample.
pub instruction: Option<String>,
}
/// Pair label for supervised pair batches.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum PairLabel {
/// Anchor and candidate are semantically aligned.
Positive,
/// Anchor and candidate are semantically mismatched.
Negative,
}
/// Batch of pairs.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SampleBatch {
/// Pair samples contained in this batch.
pub pairs: Vec<SamplePair>,
}
impl SampleBatch {
/// Returns `true` when the batch has no pairs.
pub fn is_empty(&self) -> bool {
self.pairs.is_empty()
}
}
/// Batch of triplets.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TripletBatch {
/// Triplet samples contained in this batch.
pub triplets: Vec<SampleTriplet>,
}
impl TripletBatch {
/// Returns `true` when the batch has no triplets.
pub fn is_empty(&self) -> bool {
self.triplets.is_empty()
}
}
/// A single text sample (chunk + weight).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TextSample {
/// Recipe name used to generate this sample.
pub recipe: String,
/// Chunk payload used for this text sample.
pub chunk: RecordChunk,
/// Training weight for this sample.
pub weight: f32,
/// Optional instruction/prompt hint for this sample.
pub instruction: Option<String>,
}
/// Batch of text samples.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TextBatch {
/// Text samples contained in this batch.
pub samples: Vec<TextSample>,
}
impl TextBatch {
/// Returns `true` when the batch has no text samples.
pub fn is_empty(&self) -> bool {
self.samples.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::{TimeZone, Utc};
fn sample_chunk(id: &str) -> RecordChunk {
RecordChunk {
record_id: id.to_string(),
section_idx: 0,
view: ChunkView::SummaryFallback {
strategy: "test".to_string(),
weight: 1.0,
},
text: "text".to_string(),
tokens_estimate: 4,
quality: QualityScore::default(),
}
}
#[test]
fn quality_score_defaults_to_medium_trust() {
let quality = QualityScore::default();
assert!((quality.trust - 0.5).abs() < f32::EPSILON);
}
#[test]
fn batch_is_empty_helpers_match_contents() {
let empty_pairs = SampleBatch { pairs: Vec::new() };
assert!(empty_pairs.is_empty());
let non_empty_pairs = SampleBatch {
pairs: vec![SamplePair {
recipe: "r".to_string(),
anchor: sample_chunk("a"),
positive: sample_chunk("b"),
weight: 1.0,
instruction: None,
label: PairLabel::Positive,
reason: Some("test".to_string()),
}],
};
assert!(!non_empty_pairs.is_empty());
let empty_triplets = TripletBatch {
triplets: Vec::new(),
};
assert!(empty_triplets.is_empty());
let non_empty_triplets = TripletBatch {
triplets: vec![SampleTriplet {
recipe: "r".to_string(),
anchor: sample_chunk("a"),
positive: sample_chunk("b"),
negative: sample_chunk("c"),
weight: 1.0,
instruction: Some("hint".to_string()),
}],
};
assert!(!non_empty_triplets.is_empty());
let empty_text = TextBatch {
samples: Vec::new(),
};
assert!(empty_text.is_empty());
let non_empty_text = TextBatch {
samples: vec![TextSample {
recipe: "r".to_string(),
chunk: sample_chunk("t"),
weight: 1.0,
instruction: None,
}],
};
assert!(!non_empty_text.is_empty());
}
#[test]
fn data_record_roundtrip_basics_are_constructible() {
let now = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
let record = DataRecord {
id: "source_a::1".to_string(),
source: "source_a".to_string(),
created_at: now,
updated_at: now,
quality: QualityScore { trust: 0.9 },
taxonomy: vec!["topic:news".to_string()],
sections: vec![RecordSection {
role: SectionRole::Anchor,
heading: Some("headline".to_string()),
text: "body".to_string(),
sentences: vec!["body".to_string()],
}],
meta_prefix: None,
};
assert_eq!(record.source, "source_a");
assert_eq!(record.sections.len(), 1);
assert!(matches!(record.sections[0].role, SectionRole::Anchor));
}
}