Coverage for app / router / app / generations / router.py: 94%

49 statements  

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

1"""Generative invocations — the "why does this exist?" read path. 

2 

3A resource's history says an edit was AI-generated and links a 

4``generation_id``; these endpoints resolve that id to the invocation itself: 

5which flow, what arguments the user gave, which model answered, what it 

6warned about, and which resources came out of it. 

7 

8Read-only by design. Runs are written by the flows that perform them 

9(``app.services.generation``) and are never edited or deleted — a mutable 

10audit trail is not one. 

11""" 

12 

13import logging 

14from typing import Optional 

15from uuid import UUID 

16 

17from fastapi import APIRouter, Depends, HTTPException, Query, status 

18from sqlalchemy.orm import Session 

19 

20from app.db.postgres.crud_schemas import Schema 

21from app.db.postgres.enums import GenerationEnum, HistoryEnum 

22from app.db.postgres.models import GenerationRun, ResourceVersion, User 

23from app.dependency.base import get_db 

24from app.dependency.user.context import get_current_user 

25 

26logger = logging.getLogger(__name__) 

27 

28generations_router = APIRouter(prefix="/generations", tags=["App - Generations"]) 

29 

30 

31def _actor_names(db: Session, runs: list[GenerationRun]) -> dict[UUID, str]: 

32 """Resolve each run's actor to a display name, in one query. 

33 

34 Not the caller's name: a superuser reading somebody else's run must see 

35 who actually invoked the flow, and "who ran this?" is half of what the 

36 provenance view answers. 

37 """ 

38 actor_ids = {run.actor_user_id for run in runs if run.actor_user_id} 

39 if not actor_ids: 

40 return {} 

41 rows = db.query(User).filter(User.id.in_(actor_ids)).all() 

42 return {user.id: user.name for user in rows if user.name} 

43 

44 

45def _read( 

46 run: GenerationRun, actor_name: Optional[str] = None 

47) -> Schema.Generation.Read: 

48 return Schema.Generation.Read( 

49 id=run.id, 

50 flow=run.flow, 

51 status=run.status, 

52 arguments=run.arguments if isinstance(run.arguments, dict) else {}, 

53 ai_model_id=run.ai_model_id, 

54 provider=run.provider, 

55 model_name=run.model_name, 

56 target_resource_type=run.target_resource_type, 

57 target_resource_id=run.target_resource_id, 

58 warnings=run.warnings if isinstance(run.warnings, list) else None, 

59 error=run.error, 

60 actor_user_id=run.actor_user_id, 

61 actor_name=actor_name, 

62 created_at=run.created_at, 

63 applied_at=run.applied_at, 

64 ) 

65 

66 

67def _owned(db: Session, generation_id: UUID, current_user: User) -> GenerationRun: 

68 """Fetch a run the caller is entitled to see. 

69 

70 A run is scoped to the user who invoked it. There is no ownership 

71 hierarchy to fall back on — the run predates the resources it created, so 

72 it cannot borrow their org/project scope — which makes actor identity the 

73 only meaningful check. Superusers see everything, as elsewhere. 

74 """ 

75 run = db.get(GenerationRun, generation_id) 

76 if not run: 

77 raise HTTPException( 

78 status_code=status.HTTP_404_NOT_FOUND, detail="Generation not found" 

79 ) 

80 if not current_user.is_superuser and run.actor_user_id != current_user.id: 

81 raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden") 

82 return run 

83 

84 

85@generations_router.get("", response_model=Schema.Generation.List) 

86def list_generations( 

87 flow: Optional[GenerationEnum.Flow] = None, 

88 generation_status: Optional[GenerationEnum.Status] = Query( 

89 default=None, alias="status" 

90 ), 

91 limit: int = 50, 

92 offset: int = 0, 

93 db: Session = Depends(get_db), 

94 current_user: User = Depends(get_current_user), 

95): 

96 """The caller's generative invocations in the request's workspace, 

97 newest first.""" 

98 from app.dependency.workspace import request_workspace 

99 

100 query = db.query(GenerationRun).filter( 

101 GenerationRun.actor_user_id == current_user.id, 

102 request_workspace(db, current_user).made_here(GenerationRun), 

103 ) 

104 if flow: 

105 query = query.filter(GenerationRun.flow == flow) 

106 if generation_status: 

107 query = query.filter(GenerationRun.status == generation_status) 

108 

109 rows = query.order_by(GenerationRun.created_at.desc()).all() 

110 page = rows[offset : offset + limit] 

111 names = _actor_names(db, page) 

112 return Schema.Generation.List( 

113 generations=[_read(run, names.get(run.actor_user_id)) for run in page], 

114 total=len(rows), 

115 ) 

116 

117 

118@generations_router.get( 

119 "/{generation_id}", response_model=Schema.Generation.ReadWithProduced 

120) 

121def get_generation( 

122 generation_id: UUID, 

123 db: Session = Depends(get_db), 

124 current_user: User = Depends(get_current_user), 

125): 

126 """One invocation, its exact arguments, and what it produced. 

127 

128 ``produced`` is derived from the version trail rather than from a 

129 join table: every resource a run created has a ``created`` version 

130 carrying the run's id, so the audit trail is the index. That also means a 

131 resource deleted since still appears here, which is the point. 

132 """ 

133 run = _owned(db, generation_id, current_user) 

134 

135 produced_versions = ( 

136 db.query(ResourceVersion) 

137 .filter( 

138 ResourceVersion.generation_id == run.id, 

139 ResourceVersion.action == HistoryEnum.Action.created, 

140 ) 

141 .order_by(ResourceVersion.created_at.asc()) 

142 .all() 

143 ) 

144 

145 produced = [] 

146 for version in produced_versions: 

147 snapshot = version.snapshot if isinstance(version.snapshot, dict) else {} 

148 produced.append( 

149 Schema.Generation.ProducedResource( 

150 resource_type=version.resource_type, 

151 resource_id=version.resource_id, 

152 name=snapshot.get("name"), 

153 ) 

154 ) 

155 

156 base = _read(run, _actor_names(db, [run]).get(run.actor_user_id)) 

157 return Schema.Generation.ReadWithProduced(**base.model_dump(), produced=produced)