@@ -4159,10 +4159,10 @@ async def _invalidate_facts_from_mental_models(
41594159 fact_ids : list [str ],
41604160 ) -> int :
41614161 """
4162- Remove fact IDs from mental model observations when memories are deleted.
4162+ Remove fact IDs from mental model source_memory_ids when memories are deleted.
41634163
4164- Uses JSONB path operations to find and update mental models that reference
4165- the deleted fact IDs in their observations .
4164+ Mental models are now stored in memory_units with fact_type='mental_model'
4165+ and have a source_memory_ids column (UUID[]) tracking their source memories .
41664166
41674167 Args:
41684168 conn: Database connection
@@ -4175,45 +4175,29 @@ async def _invalidate_facts_from_mental_models(
41754175 if not fact_ids :
41764176 return 0
41774177
4178- # Convert fact_ids to a jsonb array for efficient comparison
4179- import json
4178+ # Convert string IDs to UUIDs for the array comparison
4179+ import uuid as uuid_module
41804180
4181- fact_ids_json = json . dumps ( fact_ids )
4181+ fact_uuids = [ uuid_module . UUID ( fid ) for fid in fact_ids ]
41824182
4183- # Update mental models by removing the deleted fact IDs from all observations
4184- # This uses jsonb_set to update each observation's fact_ids array
4183+ # Update mental models (memory_units with fact_type='mental_model')
4184+ # by removing the deleted fact IDs from source_memory_ids
4185+ # Use array subtraction: source_memory_ids - deleted_ids
41854186 result = await conn .execute (
41864187 f"""
4187- UPDATE { fq_table ("mental_models" )}
4188- SET observations = jsonb_set(
4189- observations,
4190- '{{observations}}',
4191- (
4192- SELECT COALESCE(jsonb_agg(
4193- jsonb_set(
4194- observation,
4195- '{{fact_ids}}',
4196- (
4197- SELECT COALESCE(jsonb_agg(fid), '[]'::jsonb)
4198- FROM jsonb_array_elements_text(observation->'fact_ids') AS fid
4199- WHERE NOT (fid::text = ANY($2::text[]))
4200- )
4201- )
4202- ), '[]'::jsonb)
4203- FROM jsonb_array_elements(observations->'observations') AS observation
4204- )
4188+ UPDATE { fq_table ("memory_units" )}
4189+ SET source_memory_ids = (
4190+ SELECT COALESCE(array_agg(elem), ARRAY[]::uuid[])
4191+ FROM unnest(source_memory_ids) AS elem
4192+ WHERE elem != ALL($2::uuid[])
42054193 ),
4206- last_updated = NOW()
4194+ updated_at = NOW()
42074195 WHERE bank_id = $1
4208- AND EXISTS (
4209- SELECT 1
4210- FROM jsonb_array_elements(observations->'observations') AS observation,
4211- jsonb_array_elements_text(observation->'fact_ids') AS fid
4212- WHERE fid::text = ANY($2::text[])
4213- )
4196+ AND fact_type = 'mental_model'
4197+ AND source_memory_ids && $2::uuid[]
42144198 """ ,
42154199 bank_id ,
4216- fact_ids ,
4200+ fact_uuids ,
42174201 )
42184202
42194203 # Parse the result to get number of updated rows
0 commit comments