1use std::sync::Arc;
13use std::time::{SystemTime, UNIX_EPOCH};
14
15use tracing::{info, warn};
16
17use ailake_catalog::{
18 make_multi_column_data_file_entry, new_snapshot_id, CatalogProvider, ExtraVectorIndex,
19 NewSnapshot, SnapshotOperation, TableIdent, VectorIndexInfo,
20};
21use ailake_core::{AilakeError, AilakeResult, VectorStoragePolicy};
22use ailake_file::{AilakeFileReader, AilakeFileWriter, VectorColumnBatch};
23use ailake_store::Store;
24use ailake_vec::compute_centroid_and_radius;
25use arrow_array::{
26 Array, Float32Array, RecordBatch, TimestampMicrosecondArray, TimestampNanosecondArray,
27};
28use arrow_schema::{DataType, Field};
29
30const LAST_ACCESSED_COL: &str = "last_accessed_at";
31const RECENCY_WEIGHT_COL: &str = "recency_weight";
32
33pub struct MemoryDecayJob {
49 catalog: Arc<dyn CatalogProvider>,
50 store: Arc<dyn Store>,
51 policy: VectorStoragePolicy,
52 pub decay_lambda: f32,
55}
56
57impl MemoryDecayJob {
58 pub fn new(
59 catalog: Arc<dyn CatalogProvider>,
60 store: Arc<dyn Store>,
61 policy: VectorStoragePolicy,
62 decay_lambda: f32,
63 ) -> Self {
64 Self {
65 catalog,
66 store,
67 policy,
68 decay_lambda,
69 }
70 }
71
72 pub async fn run(&self, table: &TableIdent) -> AilakeResult<usize> {
77 let files = self.catalog.list_files(table, None).await?;
78 if files.is_empty() {
79 return Ok(0);
80 }
81
82 let today_day = current_day_since_epoch();
83 let mut new_entries = Vec::with_capacity(files.len());
84 let mut updated = 0usize;
85
86 for file_entry in &files {
87 let file_bytes = self.store.get(&file_entry.path).await?;
88 let orig_bytes = file_bytes.clone();
90 let reader =
91 AilakeFileReader::new(file_bytes, &self.policy.column_name, self.policy.dim);
92
93 if !reader.is_ailake_file() {
94 new_entries.push(file_entry.clone());
96 continue;
97 }
98
99 let (batch, embeddings) = match reader.read_parquet() {
100 Ok(pair) => pair,
101 Err(e) => {
102 warn!(
103 "ailake: MemoryDecayJob skipping {} — read error: {}",
104 file_entry.path, e
105 );
106 new_entries.push(file_entry.clone());
107 continue;
108 }
109 };
110
111 if batch.column_by_name(LAST_ACCESSED_COL).is_none() {
112 new_entries.push(file_entry.clone());
114 continue;
115 }
116
117 let updated_batch = apply_decay(&batch, today_day, self.decay_lambda)?;
118
119 let extra_embeddings: Vec<(String, u32, Vec<Vec<f32>>)> = file_entry
121 .extra_vector_indexes
122 .iter()
123 .filter_map(|xi| {
124 let r = AilakeFileReader::new(orig_bytes.clone(), &xi.column, xi.dim);
125 r.read_parquet()
126 .ok()
127 .map(|(_, embs)| (xi.column.clone(), xi.dim, embs))
128 })
129 .collect();
130
131 let file_writer = AilakeFileWriter::new(self.policy.clone());
133 let new_bytes = if extra_embeddings.is_empty() {
134 file_writer.write(&updated_batch, &embeddings)?
135 } else {
136 let extra_policies: Vec<VectorStoragePolicy> = extra_embeddings
138 .iter()
139 .map(|(col, dim, _)| VectorStoragePolicy {
140 column_name: col.clone(),
141 dim: *dim,
142 metric: self.policy.metric,
143 precision: self.policy.precision,
144 pq: None,
145 keep_raw_for_reranking: false,
146 pre_normalize: false,
147 hnsw_m: None,
148 hnsw_ef_construction: None,
149 ivf_residual: false,
150 embedding_model: None,
151 modality: None,
152 partition_by: None,
153 partition_value: None,
154 partition_column_type: None,
155 partition_fields: vec![],
156 })
157 .collect();
158 let primary_col = VectorColumnBatch {
159 policy: &self.policy,
160 embeddings: &embeddings,
161 };
162 let mut col_batches: Vec<VectorColumnBatch<'_>> = vec![primary_col];
163 for (policy, (_, _, embs)) in extra_policies.iter().zip(extra_embeddings.iter()) {
164 col_batches.push(VectorColumnBatch {
165 policy,
166 embeddings: embs,
167 });
168 }
169 file_writer.write_multi(&updated_batch, &col_batches)?
170 };
171 let new_size = new_bytes.len() as u64;
172 let new_bytes_ref = new_bytes.clone();
174 self.store.put(&file_entry.path, new_bytes.clone()).await?;
175
176 let centroid = compute_centroid_and_radius(&embeddings, self.policy.metric);
177 let new_reader =
178 AilakeFileReader::new(new_bytes, &self.policy.column_name, self.policy.dim);
179 let header = new_reader.read_header()?;
180 let ailk_start = new_reader.ailk_offset()?;
181
182 let new_extra: Vec<ExtraVectorIndex> = extra_embeddings
184 .iter()
185 .filter_map(|(col, dim, _)| {
186 let xr = AilakeFileReader::new(new_bytes_ref.clone(), col, *dim);
187 let xailk = xr.ailk_offset_for_column(col).ok()?;
188 let xhdr = xr.read_header_for_column(col).ok()?;
189 Some(ExtraVectorIndex {
190 column: col.clone(),
191 dim: *dim,
192 hnsw_offset: xailk + xhdr.hnsw_offset,
193 hnsw_len: xhdr.hnsw_len,
194 centroid_b64: None,
195 radius: None,
196 })
197 })
198 .collect();
199
200 let mut new_entry = make_multi_column_data_file_entry(
201 &file_entry.path,
202 updated_batch.num_rows() as u64,
203 new_size,
204 ¢roid,
205 VectorIndexInfo {
206 column: &self.policy.column_name,
207 dim: self.policy.dim,
208 hnsw_offset: ailk_start + header.hnsw_offset,
209 hnsw_len: header.hnsw_len,
210 },
211 &new_extra,
212 );
213 new_entry.deletion_vector = file_entry.deletion_vector.clone();
218 new_entries.push(new_entry);
219 updated += 1;
220 }
221
222 if updated == 0 {
223 info!(
224 "ailake: MemoryDecayJob — no files with last_accessed_at column; skipping commit"
225 );
226 return Ok(0);
227 }
228
229 let snap = NewSnapshot {
230 snapshot_id: new_snapshot_id(),
231 parent_snapshot_id: None,
232 files: new_entries,
233 operation: SnapshotOperation::Overwrite,
234 iceberg_schema: None,
235 extra_properties: std::collections::HashMap::new(),
236 bloom_filters: vec![],
237 equality_delete_files: vec![],
238 };
239 self.catalog.commit_snapshot(table, snap).await?;
240 info!(
241 "ailake: MemoryDecayJob — updated recency_weight in {} files (lambda={})",
242 updated, self.decay_lambda
243 );
244 Ok(updated)
245 }
246}
247
248fn days_old_vec(col: &Arc<dyn Array>, today_day: i64) -> AilakeResult<Vec<f32>> {
250 if let Some(ts) = col.as_any().downcast_ref::<TimestampNanosecondArray>() {
251 return Ok((0..ts.len())
252 .map(|i| {
253 if !ts.is_valid(i) {
254 return 0.0f32;
255 }
256 let day = ts.value(i) / (86_400 * 1_000_000_000i64);
257 (today_day - day).max(0) as f32
258 })
259 .collect());
260 }
261 if let Some(ts) = col.as_any().downcast_ref::<TimestampMicrosecondArray>() {
262 return Ok((0..ts.len())
263 .map(|i| {
264 if !ts.is_valid(i) {
265 return 0.0f32;
266 }
267 let day = ts.value(i) / (86_400 * 1_000_000i64);
268 (today_day - day).max(0) as f32
269 })
270 .collect());
271 }
272 if let Some(sa) = col.as_any().downcast_ref::<arrow_array::StringArray>() {
273 return Ok((0..sa.len())
274 .map(|i| {
275 if !sa.is_valid(i) {
276 return 0.0f32;
277 }
278 let access_day = parse_iso_date_days(sa.value(i)).unwrap_or(today_day);
279 (today_day - access_day).max(0) as f32
280 })
281 .collect());
282 }
283 Err(AilakeError::Catalog(
284 "last_accessed_at must be Timestamp(Nanosecond/Microsecond) or Utf8".into(),
285 ))
286}
287
288fn apply_decay(batch: &RecordBatch, today_day: i64, lambda: f32) -> AilakeResult<RecordBatch> {
290 let col = batch
291 .column_by_name(LAST_ACCESSED_COL)
292 .ok_or_else(|| AilakeError::Catalog("last_accessed_at column not found".into()))?;
293
294 let days_old = days_old_vec(col, today_day)?;
295 let new_weights: Vec<f32> = days_old.into_iter().map(|d| (-lambda * d).exp()).collect();
296
297 let new_weight_array = Arc::new(Float32Array::from(new_weights));
298
299 let old_schema = batch.schema();
301 let decay_field = Field::new(RECENCY_WEIGHT_COL, DataType::Float32, false);
302
303 let mut new_fields: Vec<arrow_schema::FieldRef> = old_schema.fields().iter().cloned().collect();
304 let mut new_columns: Vec<Arc<dyn Array>> = (0..batch.num_columns())
305 .map(|i| batch.column(i).clone())
306 .collect();
307
308 if let Some(pos) = old_schema
309 .fields()
310 .iter()
311 .position(|f| f.name() == RECENCY_WEIGHT_COL)
312 {
313 new_fields[pos] = Arc::new(decay_field);
314 new_columns[pos] = new_weight_array;
315 } else {
316 new_fields.push(Arc::new(decay_field));
317 new_columns.push(new_weight_array);
318 }
319
320 let new_schema = Arc::new(arrow_schema::Schema::new(new_fields));
321 RecordBatch::try_new(new_schema, new_columns).map_err(|e| AilakeError::Arrow(e.to_string()))
322}
323
324fn parse_iso_date_days(s: &str) -> Option<i64> {
327 if s.len() < 10 {
328 return None;
329 }
330 let y: i64 = s[0..4].parse().ok()?;
331 let m: i64 = s[5..7].parse().ok()?;
332 let d: i64 = s[8..10].parse().ok()?;
333 let a = (14 - m) / 12;
335 let y2 = y + 4800 - a;
336 let m2 = m + 12 * a - 3;
337 let jdn = d + (153 * m2 + 2) / 5 + 365 * y2 + y2 / 4 - y2 / 100 + y2 / 400 - 32045;
338 Some(jdn - 2440588)
340}
341
342fn current_day_since_epoch() -> i64 {
343 SystemTime::now()
344 .duration_since(UNIX_EPOCH)
345 .map(|d| d.as_secs() as i64 / 86400)
346 .unwrap_or(0)
347}
348
349#[cfg(test)]
350mod tests {
351 use super::*;
352
353 #[test]
354 fn parse_iso_date_unix_epoch() {
355 assert_eq!(parse_iso_date_days("1970-01-01T00:00:00"), Some(0));
356 }
357
358 #[test]
359 fn parse_iso_date_known_date() {
360 let days = parse_iso_date_days("2024-01-15").unwrap();
362 assert_eq!(days, 19737);
364 }
365
366 #[test]
367 fn parse_iso_date_returns_none_on_short_string() {
368 assert!(parse_iso_date_days("2024").is_none());
369 assert!(parse_iso_date_days("").is_none());
370 }
371
372 #[test]
373 fn apply_decay_updates_recency_weight() {
374 use arrow_array::StringArray;
375 use arrow_schema::{Field, Schema};
376
377 let today = current_day_since_epoch();
378 let past_day = today - 10;
380 let y = 1970 + past_day / 365; let past_str = "2024-01-05T00:00:00"; let schema = Arc::new(Schema::new(vec![
385 Field::new(LAST_ACCESSED_COL, DataType::Utf8, true),
386 Field::new(RECENCY_WEIGHT_COL, DataType::Float32, false),
387 ]));
388 let batch = RecordBatch::try_new(
389 schema,
390 vec![
391 Arc::new(StringArray::from(vec![past_str])),
392 Arc::new(Float32Array::from(vec![1.0f32])),
393 ],
394 )
395 .unwrap();
396
397 let today_day = 19737i64;
399 let result = apply_decay(&batch, today_day, 0.1).unwrap();
400 let weights = result
401 .column_by_name(RECENCY_WEIGHT_COL)
402 .unwrap()
403 .as_any()
404 .downcast_ref::<Float32Array>()
405 .unwrap();
406
407 let w = weights.value(0);
408 let expected = (-0.1f32 * 10.0).exp();
410 assert!((w - expected).abs() < 0.001, "expected {expected}, got {w}");
411 let _ = y; }
413
414 #[test]
415 fn apply_decay_handles_timestamp_nanosecond() {
416 use arrow_schema::{Field, Schema, TimeUnit};
417
418 let day_19727_ns: i64 = 19727i64 * 86_400 * 1_000_000_000;
421
422 let schema = Arc::new(Schema::new(vec![
423 Field::new(
424 LAST_ACCESSED_COL,
425 DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
426 true,
427 ),
428 Field::new(RECENCY_WEIGHT_COL, DataType::Float32, false),
429 ]));
430 let batch = RecordBatch::try_new(
431 schema,
432 vec![
433 Arc::new(TimestampNanosecondArray::from(vec![day_19727_ns]).with_timezone("UTC")),
434 Arc::new(Float32Array::from(vec![1.0f32])),
435 ],
436 )
437 .unwrap();
438
439 let today_day = 19737i64;
441 let result = apply_decay(&batch, today_day, 0.1).unwrap();
442 let weights = result
443 .column_by_name(RECENCY_WEIGHT_COL)
444 .unwrap()
445 .as_any()
446 .downcast_ref::<Float32Array>()
447 .unwrap();
448 let w = weights.value(0);
449 let expected = (-0.1f32 * 10.0).exp();
450 assert!((w - expected).abs() < 0.001, "expected {expected}, got {w}");
451 }
452
453 #[test]
454 fn now_ns_is_recent() {
455 let floor_2025_ns: i64 = 55 * 365 * 86_400 * 1_000_000_000i64; let t = ailake_core::now_ns();
458 assert!(
459 t > floor_2025_ns,
460 "now_ns() returned suspiciously small value: {t}"
461 );
462 }
463}