Coverage for app / db / postgres / mixin.py: 100%

77 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1from sqlalchemy import ( 

2 Boolean, 

3 CheckConstraint, 

4 Column, 

5 Enum, 

6 DateTime, 

7 ForeignKey, 

8 Integer, 

9 Text, 

10) 

11from sqlalchemy.orm import declared_attr 

12from sqlalchemy.dialects.postgresql import UUID 

13from .enums import OwnerEnum, RunnableEnum 

14from app.util.time import aware_utcnow 

15 

16 

17_OWNER_COUNT = ( 

18 "(owner_user_id IS NOT NULL)::int + " 

19 "(owner_organisation_id IS NOT NULL)::int + " 

20 "(owner_project_id IS NOT NULL)::int" 

21) 

22 

23 

24def ownership_constraint( 

25 table_name: str, *, allow_system: bool = False 

26) -> CheckConstraint: 

27 """Enforce exactly one of the three owner FK columns is non-null. 

28 

29 ``allow_system`` admits the one exception, for tables carrying 

30 :class:`SystemMixin`: a platform-managed row has *no* owner, and only a 

31 row flagged ``is_system`` may. The flag and the missing owner are tied 

32 together here so neither can occur without the other — an ownerless user 

33 row would otherwise be readable by everyone (see ``verify_resource_access``). 

34 """ 

35 if not allow_system: 

36 return CheckConstraint(f"{_OWNER_COUNT} = 1", name=f"ck_{table_name}_one_owner") 

37 return CheckConstraint( 

38 f"(NOT is_system AND {_OWNER_COUNT} = 1) OR (is_system AND {_OWNER_COUNT} = 0)", 

39 name=f"ck_{table_name}_one_owner", 

40 ) 

41 

42 

43class FKMixin: 

44 class User: 

45 user_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False) 

46 

47 class Nullable: 

48 user_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=True) 

49 

50 class Agent: 

51 agent_id = Column( 

52 UUID(as_uuid=True), 

53 ForeignKey("agents.id"), 

54 nullable=False, 

55 ) 

56 

57 class Child: 

58 agent_id = Column( 

59 UUID(as_uuid=True), 

60 ForeignKey("agents.id", ondelete="CASCADE"), 

61 nullable=False, 

62 ) 

63 

64 class Nullable: 

65 agent_id = Column( 

66 UUID(as_uuid=True), 

67 ForeignKey("agents.id"), 

68 nullable=True, 

69 ) 

70 

71 class NullableChild: 

72 agent_id = Column( 

73 UUID(as_uuid=True), 

74 ForeignKey("agents.id", ondelete="CASCADE"), 

75 nullable=True, 

76 ) 

77 

78 class Project: 

79 project_id = Column( 

80 UUID(as_uuid=True), 

81 ForeignKey("projects.id"), 

82 nullable=False, 

83 ) 

84 

85 class Child: 

86 project_id = Column( 

87 UUID(as_uuid=True), 

88 ForeignKey("projects.id", ondelete="CASCADE"), 

89 nullable=False, 

90 ) 

91 

92 class Role: 

93 role_id = Column(UUID(as_uuid=True), ForeignKey("roles.id"), nullable=False) 

94 

95 class Knowledge: 

96 knowledge_id = Column( 

97 UUID(as_uuid=True), 

98 ForeignKey("knowledge.id"), 

99 nullable=False, 

100 ) 

101 

102 class Child: 

103 knowledge_id = Column( 

104 UUID(as_uuid=True), 

105 ForeignKey("knowledge.id", ondelete="CASCADE"), 

106 nullable=False, 

107 ) 

108 

109 class Conversation: 

110 conversation_id = Column( 

111 UUID(as_uuid=True), 

112 ForeignKey("conversations.id"), 

113 nullable=False, 

114 ) 

115 

116 class Child: 

117 conversation_id = Column( 

118 UUID(as_uuid=True), 

119 ForeignKey("conversations.id", ondelete="CASCADE"), 

120 nullable=False, 

121 ) 

122 

123 

124class OwnableMixin: 

125 class Resource: 

126 """ 

127 Ownership via three nullable FK columns — exactly one must be set. 

128 Enforced by a per-table CheckConstraint (ownership_constraint()). 

129 Replaces the old polymorphic (resource_owner_type, resource_owner_id) pair. 

130 """ 

131 

132 owner_user_id = Column( 

133 UUID(as_uuid=True), 

134 ForeignKey("users.id", ondelete="CASCADE"), 

135 nullable=True, 

136 index=True, 

137 ) 

138 owner_organisation_id = Column( 

139 UUID(as_uuid=True), 

140 ForeignKey("organisations.id", ondelete="CASCADE"), 

141 nullable=True, 

142 index=True, 

143 ) 

144 owner_project_id = Column( 

145 UUID(as_uuid=True), 

146 ForeignKey("projects.id", ondelete="CASCADE"), 

147 nullable=True, 

148 index=True, 

149 ) 

150 

151 class Infra: 

152 infra_owner_type = Column( 

153 Enum(OwnerEnum.Infra, name="infra_owner_type_enum"), 

154 nullable=False, 

155 index=True, 

156 ) 

157 

158 infra_owner_id = Column( 

159 Text, 

160 nullable=False, 

161 index=True, 

162 ) 

163 

164 class LLMArtifact(FKMixin.Agent.NullableChild): 

165 # ai_model_id is a soft reference to svc-ai's llm_models.id — no FK constraint 

166 ai_model_id = Column(UUID(as_uuid=True), nullable=True, index=True) 

167 

168 

169class SystemMixin: 

170 """Platform-managed rows: CHAINR Bot, its guide, the built-in skillsets 

171 every user can grant to their own agents, the gold datasets every user 

172 can benchmark against, the built-in rules users create rules from, and 

173 the built-in dashboards every user opens. 

174 

175 A system row belongs to no user, organisation or project — every user may 

176 read it and nobody may change it through the API, superusers included. 

177 Its content is defined in code (``app.services.system_resources``) and 

178 provisioned at startup, so a release is the only way it changes, and 

179 each change still lands in its edit history. 

180 

181 Pair with ``ownership_constraint(..., allow_system=True)``. 

182 """ 

183 

184 is_system = Column( 

185 Boolean, nullable=False, default=False, server_default="false", index=True 

186 ) 

187 

188 

189class GenerationMixin: 

190 """AI-generation provenance, in two layers. 

191 

192 Every resource a user can create carries ``Tagged`` at minimum, so 

193 "was this generated, and by which invocation?" has the same answer shape 

194 everywhere. ``Provenance`` adds the parent link, for resources that a 

195 generative flow creates *alongside* an agent rather than as its subject. 

196 

197 The three columns answer three different questions and none replaces 

198 another: 

199 

200 ``is_ai_generated`` was this hand-built or generated? 

201 ``generation_id`` which invocation produced it — and, through that 

202 row, with what arguments and which model? 

203 ``generated_by_agent_id`` which agent was that invocation building, when 

204 this resource is a dependent of one? 

205 """ 

206 

207 class Tagged: 

208 """AI-generation flag plus the invocation that set it. 

209 

210 ``is_ai_generated`` is true when the row was created by a generative 

211 flow rather than by hand — kept permanently for historical reference. 

212 

213 ``generation_id`` resolves that flag to the exact 

214 :class:`~app.db.postgres.models.GenerationRun`: the flow invoked, the 

215 arguments the user supplied, and the model that answered. SET NULL 

216 rather than CASCADE for the same reason the flag is permanent — losing 

217 the detail must not silently un-generate the resource. 

218 """ 

219 

220 is_ai_generated = Column( 

221 Boolean, nullable=False, default=False, server_default="false" 

222 ) 

223 

224 generation_id = Column( 

225 UUID(as_uuid=True), 

226 ForeignKey("generation_runs.id", ondelete="SET NULL"), 

227 nullable=True, 

228 index=True, 

229 ) 

230 

231 class Provenance(Tagged): 

232 """Provenance for dependent resources created alongside an agent. 

233 

234 ``generated_by_agent_id`` points at the agent whose generative setup 

235 created this resource; SET NULL keeps the resource (and its 

236 ``is_ai_generated`` flag) if that agent is later deleted. 

237 """ 

238 

239 generated_by_agent_id = Column( 

240 UUID(as_uuid=True), 

241 ForeignKey("agents.id", ondelete="SET NULL"), 

242 nullable=True, 

243 index=True, 

244 ) 

245 

246 

247class RunnableMixin: 

248 class Status: 

249 status = Column(Enum(RunnableEnum.Status, name="runnable_status_enum")) 

250 

251 class Run(Status): 

252 started_at = Column(DateTime, default=aware_utcnow) 

253 finished_at = Column(DateTime, nullable=True) 

254 

255 

256class DateMixin: 

257 class Created: 

258 created_at = Column(DateTime, default=aware_utcnow) 

259 

260 class Updated(Created): 

261 updated_at = Column(DateTime, default=aware_utcnow, onupdate=aware_utcnow) 

262 

263 class Joined: 

264 joined_at = Column(DateTime, default=aware_utcnow) 

265 

266 class Sent: 

267 sent_at = Column(DateTime, default=aware_utcnow) 

268 

269 

270class ClonableMixin: 

271 """Where a resource was copied from (``app/services/copying.py``): the 

272 row it was made from and that row's version then, so its page can say 

273 "copied from Acme › Helper, v3" — and say when the original has moved on. 

274 A copy is independent: the original changing never reaches it. SET NULL, 

275 so deleting the original leaves the copy and forgets the link.""" 

276 

277 @declared_attr 

278 def cloned_from_id(cls): # noqa: N805 

279 return Column( 

280 UUID(as_uuid=True), 

281 ForeignKey(f"{cls.__tablename__}.id", ondelete="SET NULL"), 

282 nullable=True, 

283 index=True, 

284 ) 

285 

286 @declared_attr 

287 def cloned_from_version(cls): # noqa: N805 

288 return Column(Integer, nullable=True)