File size: 9,867 Bytes
7302343
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Feedback ingest tests — risk tier rules, deltas, full process_feedback flow.

Pure-function tests run always. DB integration tests skip when SKIP_DB_TESTS=true.
"""

from __future__ import annotations

import os
import uuid
from typing import TYPE_CHECKING

import pytest
import pytest_asyncio

if TYPE_CHECKING:
    from collections.abc import AsyncIterator

    from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
else:
    from sqlalchemy.ext.asyncio import AsyncEngine  # noqa: TC002

from memory.ingest import IngestResult, _compute_deltas, compute_risk_tier
from store.types import FeedbackInput

# === Pure-function tests (no DB) ==========================================


class TestComputeRiskTier:
    def test_new_when_no_history(self) -> None:
        assert compute_risk_tier(prior_violations=0, prior_approvals=0) == "new"

    def test_watched_at_three_violations(self) -> None:
        assert compute_risk_tier(prior_violations=3, prior_approvals=0) == "watched"

    def test_watched_at_many_violations(self) -> None:
        assert compute_risk_tier(prior_violations=10, prior_approvals=5) == "watched"

    def test_trusted_at_five_approvals_no_violations(self) -> None:
        assert compute_risk_tier(prior_violations=0, prior_approvals=5) == "trusted"

    def test_trusted_at_many_approvals(self) -> None:
        assert compute_risk_tier(prior_violations=0, prior_approvals=20) == "trusted"

    def test_neutral_with_some_approvals(self) -> None:
        assert compute_risk_tier(prior_violations=0, prior_approvals=3) == "neutral"

    def test_neutral_with_mixed(self) -> None:
        assert compute_risk_tier(prior_violations=1, prior_approvals=10) == "neutral"

    def test_neutral_with_few_violations(self) -> None:
        assert compute_risk_tier(prior_violations=2, prior_approvals=0) == "neutral"

    def test_watched_overrides_approvals(self) -> None:
        assert compute_risk_tier(prior_violations=3, prior_approvals=100) == "watched"


class TestComputeDeltas:
    def test_remove_increments_violations(self) -> None:
        assert _compute_deltas("REMOVE") == (1, 0)

    def test_approve_increments_approvals(self) -> None:
        assert _compute_deltas("APPROVE") == (0, 1)

    def test_escalate_no_change(self) -> None:
        assert _compute_deltas("ESCALATE") == (0, 0)

    def test_lock_no_change(self) -> None:
        assert _compute_deltas("LOCK") == (0, 0)


# === DB integration tests =================================================

db_tests = pytest.mark.skipif(
    os.getenv("SKIP_DB_TESTS", "false").lower() in ("true", "1", "yes"),
    reason="SKIP_DB_TESTS=true (CI without docker services)",
)


def _sub_id() -> str:
    return f"t5_{uuid.uuid4().hex[:10]}"


def _feedback(sub_id: str, **overrides: object) -> FeedbackInput:
    base: dict[str, object] = {
        "correlation_id": f"inv-fb-{uuid.uuid4().hex[:8]}",
        "subreddit_id": sub_id,
        "target_id": "t1_abc",
        "mod_action": "REMOVE",
        "raw_action": "spamlink",
        "moderator_id": "t2_mod",
        "moderator_name": "mod_user",
        "source": "verdict_card",
        "aligned": True,
    }
    base.update(overrides)
    return FeedbackInput.model_validate(base)


@pytest_asyncio.fixture
async def engine() -> AsyncIterator[AsyncEngine]:
    from api.config import get_settings
    from store.connections import close_postgres, open_postgres

    get_settings.cache_clear()
    eng = await open_postgres(get_settings())
    try:
        yield eng
    finally:
        await close_postgres(eng)


@pytest.fixture
def sessions(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]:
    from store.postgres import make_sessionmaker

    return make_sessionmaker(engine)


@db_tests
@pytest.mark.asyncio
async def test_process_feedback_happy_path(
    sessions: async_sessionmaker[AsyncSession],
) -> None:
    from memory.ingest import process_feedback
    from store.postgres import ensure_subreddit_profile, with_session

    sub = _sub_id()
    async with with_session(sessions) as s:
        await ensure_subreddit_profile(s, subreddit_id=sub, name="test")
        result = await process_feedback(
            s,
            feedback=_feedback(sub),
            target_author_id="t2_author",
            post_id="t3_post1",
        )
    assert isinstance(result, IngestResult)
    assert result.cold_start_count == 1


@db_tests
@pytest.mark.asyncio
async def test_remove_increments_violations(
    sessions: async_sessionmaker[AsyncSession],
) -> None:
    from memory.ingest import process_feedback
    from store.postgres import ensure_subreddit_profile, get_user_memory, with_session

    sub = _sub_id()
    async with with_session(sessions) as s:
        await ensure_subreddit_profile(s, subreddit_id=sub, name="test")
        await process_feedback(
            s, feedback=_feedback(sub), target_author_id="t2_author"
        )
        await process_feedback(
            s, feedback=_feedback(sub), target_author_id="t2_author"
        )
        mem = await get_user_memory(s, subreddit_id=sub, user_id="t2_author")
    assert mem is not None
    assert mem.prior_violations == 2
    assert mem.prior_approvals == 0


@db_tests
@pytest.mark.asyncio
async def test_approve_increments_approvals(
    sessions: async_sessionmaker[AsyncSession],
) -> None:
    from memory.ingest import process_feedback
    from store.postgres import ensure_subreddit_profile, get_user_memory, with_session

    sub = _sub_id()
    async with with_session(sessions) as s:
        await ensure_subreddit_profile(s, subreddit_id=sub, name="test")
        await process_feedback(
            s,
            feedback=_feedback(sub, mod_action="APPROVE"),
            target_author_id="t2_author",
        )
        mem = await get_user_memory(s, subreddit_id=sub, user_id="t2_author")
    assert mem is not None
    assert mem.prior_approvals == 1
    assert mem.prior_violations == 0


@db_tests
@pytest.mark.asyncio
async def test_risk_tier_transitions_to_watched(
    sessions: async_sessionmaker[AsyncSession],
) -> None:
    from memory.ingest import process_feedback
    from store.postgres import ensure_subreddit_profile, get_user_memory, with_session

    sub = _sub_id()
    async with with_session(sessions) as s:
        await ensure_subreddit_profile(s, subreddit_id=sub, name="test")
        for _ in range(3):
            await process_feedback(
                s, feedback=_feedback(sub), target_author_id="t2_bad"
            )
        mem = await get_user_memory(s, subreddit_id=sub, user_id="t2_bad")
    assert mem is not None
    assert mem.risk_tier == "watched"
    assert mem.prior_violations == 3


@db_tests
@pytest.mark.asyncio
async def test_risk_tier_transitions_to_trusted(
    sessions: async_sessionmaker[AsyncSession],
) -> None:
    from memory.ingest import process_feedback
    from store.postgres import ensure_subreddit_profile, get_user_memory, with_session

    sub = _sub_id()
    async with with_session(sessions) as s:
        await ensure_subreddit_profile(s, subreddit_id=sub, name="test")
        for _ in range(5):
            await process_feedback(
                s,
                feedback=_feedback(sub, mod_action="APPROVE"),
                target_author_id="t2_good",
            )
        mem = await get_user_memory(s, subreddit_id=sub, user_id="t2_good")
    assert mem is not None
    assert mem.risk_tier == "trusted"


@db_tests
@pytest.mark.asyncio
async def test_cold_start_counter_increments(
    sessions: async_sessionmaker[AsyncSession],
) -> None:
    from memory.ingest import process_feedback
    from store.postgres import ensure_subreddit_profile, with_session

    sub = _sub_id()
    async with with_session(sessions) as s:
        await ensure_subreddit_profile(s, subreddit_id=sub, name="test")
        r1 = await process_feedback(s, feedback=_feedback(sub))
        r2 = await process_feedback(s, feedback=_feedback(sub))
    assert r1.cold_start_count == 1
    assert r2.cold_start_count == 2


@db_tests
@pytest.mark.asyncio
async def test_thread_memory_updated(
    sessions: async_sessionmaker[AsyncSession],
) -> None:
    from memory.ingest import process_feedback
    from store.postgres import ensure_subreddit_profile, get_thread_memory, with_session

    sub = _sub_id()
    async with with_session(sessions) as s:
        await ensure_subreddit_profile(s, subreddit_id=sub, name="test")
        await process_feedback(
            s, feedback=_feedback(sub), post_id="t3_thread1"
        )
        tm = await get_thread_memory(s, subreddit_id=sub, post_id="t3_thread1")
    assert tm is not None
    assert len(tm.mod_actions_taken) == 1
    assert tm.mod_actions_taken[0]["action"] == "REMOVE"


@db_tests
@pytest.mark.asyncio
async def test_no_user_update_without_author(
    sessions: async_sessionmaker[AsyncSession],
) -> None:
    from memory.ingest import process_feedback
    from store.postgres import ensure_subreddit_profile, with_session

    sub = _sub_id()
    async with with_session(sessions) as s:
        await ensure_subreddit_profile(s, subreddit_id=sub, name="test")
        result = await process_feedback(s, feedback=_feedback(sub))
    assert isinstance(result, IngestResult)


@db_tests
@pytest.mark.asyncio
async def test_no_thread_update_without_post_id(
    sessions: async_sessionmaker[AsyncSession],
) -> None:
    from memory.ingest import process_feedback
    from store.postgres import ensure_subreddit_profile, get_thread_memory, with_session

    sub = _sub_id()
    async with with_session(sessions) as s:
        await ensure_subreddit_profile(s, subreddit_id=sub, name="test")
        await process_feedback(s, feedback=_feedback(sub), post_id="")
        tm = await get_thread_memory(s, subreddit_id=sub, post_id="t3_nope")
    assert tm is None