Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(teamhub): admit Wiki refreshes of different Humans without aborting each other

LeoXinge0c13ad8ddf6
diff --git a/apps/teamhub/internal/document/README.md b/apps/teamhub/internal/document/README.md
index d03263f2..1fd81fb8 100644
--- a/apps/teamhub/internal/document/README.md
+++ b/apps/teamhub/internal/document/README.md
@@ -51,6 +51,11 @@ queues a follow-up over every changed source; a meeting request is not admitted
reads text and metadata only for the sources a refresh adds or changes, so a source frozen at its published version
needs neither.
+Every refresh request of a Human, from Memory or the Web, is admitted in a `REPEATABLE READ` transaction that starts
+only after it holds that Human's admission lock, so it sees the previous admission and joins or replays it. Admissions
+of different Humans neither wait for nor abort each other, so Memory's nightly requests for every Human can run at
+once; a settlement or dispatch status change of the same Wiki is a write conflict, and the admission retries.
+
## History points
A History point is a Revision with a `history_trigger`, so a History Entry's ID is its Revision's ID.
diff --git a/apps/teamhub/internal/document/memory_wiki_refresh.go b/apps/teamhub/internal/document/memory_wiki_refresh.go
index 66ad99de..d0313536 100644
--- a/apps/teamhub/internal/document/memory_wiki_refresh.go
+++ b/apps/teamhub/internal/document/memory_wiki_refresh.go
@@ -71,32 +71,20 @@ func (s *Service) RequestMemoryWikiRefresh(
return MemoryWikiRefreshResult{}, err
}
}
- for attempt := 1; attempt <= memoryWikiTransactionAttempts; attempt++ {
- result, err = s.requestMemoryWikiRefreshOnce(ctx, input, refreshInput)
- if err == nil || !isRetryableDocumentTransactionError(err) || attempt == memoryWikiTransactionAttempts {
- return result, err
- }
- if waitErr := waitMemoryWikiTransactionRetry(ctx, attempt); waitErr != nil {
- return result, waitErr
- }
- }
+ err = s.admitWikiRefresh(ctx, input.TenantID, accountID, func(tx pgx.Tx) error {
+ var admitErr error
+ result, admitErr = s.requestMemoryWikiRefreshInTransaction(ctx, tx, input, refreshInput)
+ return admitErr
+ })
return result, err
}
-func (s *Service) requestMemoryWikiRefreshOnce(
+func (s *Service) requestMemoryWikiRefreshInTransaction(
ctx context.Context,
+ tx pgx.Tx,
input RequestMemoryWikiRefreshInput,
refreshInput RequestWikiRefreshInput,
) (MemoryWikiRefreshResult, error) {
- tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.Serializable})
- if err != nil {
- return MemoryWikiRefreshResult{}, err
- }
- defer func() { _ = tx.Rollback(ctx) }()
- if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`,
- "memory-wiki-source-set|"+input.TenantID+"|"+input.OwnerActorID); err != nil {
- return MemoryWikiRefreshResult{}, err
- }
wikiID, err := ensureMemoryWikiRoot(ctx, tx, input.TenantID, input.OwnerActorID)
if err != nil {
return MemoryWikiRefreshResult{}, err
@@ -131,9 +119,6 @@ func (s *Service) requestMemoryWikiRefreshOnce(
if err != nil {
return MemoryWikiRefreshResult{}, err
}
- if err := tx.Commit(ctx); err != nil {
- return MemoryWikiRefreshResult{}, err
- }
return MemoryWikiRefreshResult{WikiID: wikiID, Refresh: refresh}, nil
}
diff --git a/apps/teamhub/internal/document/wiki.go b/apps/teamhub/internal/document/wiki.go
index 135d7854..b23abc8c 100644
--- a/apps/teamhub/internal/document/wiki.go
+++ b/apps/teamhub/internal/document/wiki.go
@@ -983,31 +983,17 @@ func (s *Service) RequestWikiRefresh(
} else if lookupErr != nil {
return WikiRefreshResult{}, lookupErr
}
- var result WikiRefreshResult
- var err error
- for attempt := 1; attempt <= memoryWikiTransactionAttempts; attempt++ {
- if !replayed && attempt == 1 && input.CaptureID == "" {
- if prepareErr := s.prepareWikiSources(ctx, input); prepareErr != nil {
- return WikiRefreshResult{}, prepareErr
- }
- }
- tx, beginErr := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.Serializable})
- if beginErr != nil {
- return WikiRefreshResult{}, beginErr
- }
- result, err = s.requestWikiRefreshInTransaction(ctx, tx, input, requestHash)
- if err == nil {
- err = tx.Commit(ctx)
- } else {
- _ = tx.Rollback(ctx)
- }
- if err == nil || !isRetryableDocumentTransactionError(err) || attempt == memoryWikiTransactionAttempts {
- return result, err
- }
- if waitErr := waitMemoryWikiTransactionRetry(ctx, attempt); waitErr != nil {
- return result, waitErr
+ if !replayed && input.CaptureID == "" {
+ if err := s.prepareWikiSources(ctx, input); err != nil {
+ return WikiRefreshResult{}, err
}
}
+ var result WikiRefreshResult
+ err := s.admitWikiRefresh(ctx, input.TenantID, input.AccountID, func(tx pgx.Tx) error {
+ var admitErr error
+ result, admitErr = s.requestWikiRefreshInTransaction(ctx, tx, input, requestHash)
+ return admitErr
+ })
return result, err
}
@@ -1084,17 +1070,13 @@ func (s *Service) requestWikiRefreshInTransaction(
return result, nil
}
-// lockWikiRefreshTarget serializes source-set changes of the requesting Human
-// and locks their Wiki and its active generator Agent.
+// lockWikiRefreshTarget locks the requesting Human's Wiki and its active
+// generator Agent. The caller already holds the Human's admission lock.
func lockWikiRefreshTarget(ctx context.Context, tx pgx.Tx, input RequestWikiRefreshInput) (wikiRefreshTarget, error) {
actorID, err := resolveActiveHumanActorTx(ctx, tx, input.AccountID, input.TenantID)
if err != nil {
return wikiRefreshTarget{}, err
}
- if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`,
- "memory-wiki-source-set|"+input.TenantID+"|"+actorID); err != nil {
- return wikiRefreshTarget{}, err
- }
var target wikiRefreshTarget
err = tx.QueryRow(ctx, `SELECT id,coalesce(current_revision_id,'')
FROM personal_wikis
diff --git a/apps/teamhub/internal/document/wiki_refresh_admission.go b/apps/teamhub/internal/document/wiki_refresh_admission.go
new file mode 100644
index 00000000..486e0402
--- /dev/null
+++ b/apps/teamhub/internal/document/wiki_refresh_admission.go
@@ -0,0 +1,55 @@
+package document
+
+import (
+ "context"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+)
+
+// admitWikiRefresh runs admit as one Human's Wiki refresh admission and
+// retries it after a serialization failure.
+//
+// Admission runs in REPEATABLE READ under the Human's admission lock, taken
+// before the transaction starts so that each snapshot already holds the
+// previous admission's commit. Admissions of different Humans write different
+// rows but share pages of small indexes, such as the one active refresh per
+// Wiki, so SERIALIZABLE predicate locks aborted them against each other.
+// Within one Human the lock orders admissions, and settlement and dispatch
+// update the Wiki and refresh rows admission locks, so they surface as write
+// conflicts that retry on a fresh snapshot.
+func (s *Service) admitWikiRefresh(ctx context.Context, tenantID, accountID string, admit func(pgx.Tx) error) error {
+ key := "wiki-refresh-admission|" + tenantID + "|" + accountID
+ connection, err := s.pool.Acquire(ctx)
+ if err != nil {
+ return err
+ }
+ queries := store.New(connection)
+ if err := queries.AcquireAdvisorySessionLock(ctx, key); err != nil {
+ discardPoolConnection(connection)
+ return err
+ }
+ defer func() {
+ unlockContext, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if unlocked, err := queries.ReleaseAdvisorySessionLock(unlockContext, key); err != nil || !unlocked {
+ // A session that may still hold the lock must not return to the pool.
+ discardPoolConnection(connection)
+ return
+ }
+ connection.Release()
+ }()
+ return retryWikiTransaction(ctx, func() error {
+ tx, err := connection.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead})
+ if err != nil {
+ return err
+ }
+ defer func() { _ = tx.Rollback(ctx) }()
+ if err := admit(tx); err != nil {
+ return err
+ }
+ return tx.Commit(ctx)
+ })
+}
diff --git a/apps/teamhub/internal/store/identity.sql.go b/apps/teamhub/internal/store/identity.sql.go
index c26d2d73..c5dabc17 100644
--- a/apps/teamhub/internal/store/identity.sql.go
+++ b/apps/teamhub/internal/store/identity.sql.go
@@ -11,6 +11,15 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
+const acquireAdvisorySessionLock = `-- name: AcquireAdvisorySessionLock :exec
+SELECT pg_advisory_lock(hashtextextended($1, 0))
+`
+
+func (q *Queries) AcquireAdvisorySessionLock(ctx context.Context, lockKey string) error {
+ _, err := q.db.Exec(ctx, acquireAdvisorySessionLock, lockKey)
+ return err
+}
+
const acquireAdvisoryTransactionLock = `-- name: AcquireAdvisoryTransactionLock :exec
SELECT pg_advisory_xact_lock(hashtextextended($1, 0))
`
@@ -379,6 +388,17 @@ func (q *Queries) LockAccountPasswordHash(ctx context.Context, id string) (strin
return password_hash, err
}
+const releaseAdvisorySessionLock = `-- name: ReleaseAdvisorySessionLock :one
+SELECT pg_advisory_unlock(hashtextextended($1, 0))
+`
+
+func (q *Queries) ReleaseAdvisorySessionLock(ctx context.Context, lockKey string) (bool, error) {
+ row := q.db.QueryRow(ctx, releaseAdvisorySessionLock, lockKey)
+ var pg_advisory_unlock bool
+ err := row.Scan(&pg_advisory_unlock)
+ return pg_advisory_unlock, err
+}
+
const renewSession = `-- name: RenewSession :one
UPDATE auth_sessions
SET expires_at = LEAST(clock_timestamp() + $1::interval, created_at + $2::interval)
diff --git a/apps/teamhub/internal/store/queries/identity.sql b/apps/teamhub/internal/store/queries/identity.sql
index 67a9f58c..6769aae3 100644
--- a/apps/teamhub/internal/store/queries/identity.sql
+++ b/apps/teamhub/internal/store/queries/identity.sql
@@ -131,3 +131,9 @@ SELECT pg_advisory_xact_lock(hashtextextended(sqlc.arg(lock_key), 0));
-- name: AcquireAdvisoryTransactionSharedLock :exec
SELECT pg_advisory_xact_lock_shared(hashtextextended(sqlc.arg(lock_key), 0));
+
+-- name: AcquireAdvisorySessionLock :exec
+SELECT pg_advisory_lock(hashtextextended(sqlc.arg(lock_key), 0));
+
+-- name: ReleaseAdvisorySessionLock :one
+SELECT pg_advisory_unlock(hashtextextended(sqlc.arg(lock_key), 0));
diff --git a/apps/teamhub/tests/integration/wiki_refresh_admission_concurrency_test.go b/apps/teamhub/tests/integration/wiki_refresh_admission_concurrency_test.go
new file mode 100644
index 00000000..3d32b61c
--- /dev/null
+++ b/apps/teamhub/tests/integration/wiki_refresh_admission_concurrency_test.go
@@ -0,0 +1,176 @@
+package integration_test
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "sync"
+ "sync/atomic"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/document"
+)
+
+// Memory requests every Human's nightly Wiki refresh at the same moment.
+// Admissions of different Humans write different rows and must not abort
+// each other; requests of one Human, from Memory and from the Web, must admit
+// one refresh without a serialization failure.
+
+func TestWikiRefreshAdmissionsOfDifferentHumansDoNotConflict(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ const humans = 12
+ service, _, tracer := newWikiRefreshAdmissionFixture(t, humans)
+ results := make([]document.MemoryWikiRefreshResult, humans)
+ errs := make([]error, humans)
+ runWikiAdmissionsTogether(humans, func(index int) {
+ results[index], errs[index] = service.RequestMemoryWikiRefresh(t.Context(), document.RequestMemoryWikiRefreshInput{
+ TenantID: "tenant_document_a", OwnerActorID: wikiAdmissionHuman(index), Date: "2026-11-16",
+ })
+ })
+ for index := range humans {
+ if errs[index] != nil || results[index].Refresh.Status != document.WikiRefreshAccepted {
+ t.Fatalf("Human %d refresh=%+v err=%v", index, results[index], errs[index])
+ }
+ }
+ if failures := tracer.failures.Load(); failures != 0 {
+ t.Fatalf("admissions of different Humans aborted each other %d times", failures)
+ }
+}
+
+func TestConcurrentWikiRefreshRequestsOfOneHumanAdmitOneRefresh(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ const requests = 8
+ service, pool, tracer := newWikiRefreshAdmissionFixture(t, 1)
+ // The Web request refreshes an existing Wiki; Memory creates one only for
+ // a Human's first refresh.
+ if _, err := pool.Exec(t.Context(), `INSERT INTO personal_wikis(id,tenant_id,owner_actor_id)
+ VALUES('wiki_admission_0','tenant_document_a',$1)`, wikiAdmissionHuman(0)); err != nil {
+ t.Fatal(err)
+ }
+ refreshIDs := make([]string, requests)
+ errs := make([]error, requests)
+ runWikiAdmissionsTogether(requests, func(index int) {
+ if index%2 == 0 {
+ result, err := service.RequestMemoryWikiRefresh(t.Context(), document.RequestMemoryWikiRefreshInput{
+ TenantID: "tenant_document_a", OwnerActorID: wikiAdmissionHuman(0), Date: "2026-11-16",
+ })
+ refreshIDs[index], errs[index] = result.Refresh.ID, err
+ return
+ }
+ result, err := service.RequestWikiRefresh(t.Context(), document.RequestWikiRefreshInput{
+ AccountID: "account_admission_0", TenantID: "tenant_document_a",
+ IdempotencyKey: fmt.Sprintf("web-refresh-%d", index),
+ })
+ refreshIDs[index], errs[index] = result.ID, err
+ })
+ for index := range requests {
+ if errs[index] != nil || refreshIDs[index] == "" || refreshIDs[index] != refreshIDs[0] {
+ t.Fatalf("request %d answered refresh %q, want the one refresh %q: %v", index, refreshIDs[index], refreshIDs[0], errs[index])
+ }
+ }
+ var staging int
+ if err := pool.QueryRow(t.Context(), `SELECT count(*) FROM document_wiki_refreshes
+ WHERE wiki_id='wiki_admission_0' AND status='staging'`).Scan(&staging); err != nil || staging != 1 {
+ t.Fatalf("staging refreshes=%d err=%v", staging, err)
+ }
+ if failures := tracer.failures.Load(); failures != 0 {
+ t.Fatalf("requests of one Human aborted each other %d times", failures)
+ }
+}
+
+// serializationFailureTracer counts statements PostgreSQL aborted with a
+// serialization failure or a deadlock, including those a retry recovered.
+type serializationFailureTracer struct {
+ failures atomic.Int64
+}
+
+func (*serializationFailureTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, _ pgx.TraceQueryStartData) context.Context {
+ return ctx
+}
+
+func (tracer *serializationFailureTracer) TraceQueryEnd(_ context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
+ var postgresError *pgconn.PgError
+ if errors.As(data.Err, &postgresError) && (postgresError.Code == "40001" || postgresError.Code == "40P01") {
+ tracer.failures.Add(1)
+ }
+}
+
+// newWikiRefreshAdmissionFixture seeds Humans that each have an Another Me
+// and one indexed Room Session, and returns a Document service whose pool
+// counts serialization failures.
+func newWikiRefreshAdmissionFixture(t *testing.T, humans int) (*document.Service, *pgxpool.Pool, *serializationFailureTracer) {
+ t.Helper()
+ ctx := t.Context()
+ _, pool := newUnifiedDocumentActionsFixture(t)
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO accounts(id,email,password_hash)
+ SELECT 'account_admission_'||i,'admission-'||i||'@example.com','x' FROM generate_series(0,$1::int-1) i;
+ INSERT INTO actors(id,tenant_id,kind,display_name,account_id,handle)
+ SELECT 'actor_admission_human_'||i,'tenant_document_a','human','Human '||i,'account_admission_'||i,NULL
+ FROM generate_series(0,$1::int-1) i;
+ INSERT INTO actors(id,tenant_id,kind,display_name,account_id,handle)
+ SELECT 'actor_admission_agent_'||i,'tenant_document_a','agent','Another Me '||i,NULL,'another-me-admission-'||i
+ FROM generate_series(0,$1::int-1) i;
+ INSERT INTO agent_registrations(
+ actor_id,tenant_id,agent_management_id,status,instructions,runtime_model,created_by_actor_id,
+ computer_id,local_runtime_type,workspace_grant_id,agent_type,represented_human_actor_id
+ ) SELECT 'actor_admission_agent_'||i,'tenant_document_a','agent_admission_'||i,'active','Another Me.',
+ 'test-model','actor_admission_human_'||i,'computer_fixture','codex','grant_files','anotherme',
+ 'actor_admission_human_'||i
+ FROM generate_series(0,$1::int-1) i`, pgx.QueryExecModeSimpleProtocol, humans); err != nil {
+ t.Fatal(err)
+ }
+ for index := range humans {
+ sessionKey := fmt.Sprintf("admission-session-%d", index)
+ sourceKey := sha256.Sum256([]byte(sessionKey))
+ content := "# " + sessionKey + "\n"
+ contentKey := sha256.Sum256([]byte(content))
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO memory_index.sources(id,tenant_id,owner_id,agent_id,document_id,
+ source_path,title,active_sha256,index_profile,source_kind,origin_kind,source_uri,source_version,metadata,room_id)
+ VALUES($1,'tenant_document_a',$2,$3,$4,'memory/evidence/2026-11-16/sessions/'||$6||'.md',$6,$5,
+ 'raw-test','room_message','room','teamhub://rooms/room_document_a/messages',$5,
+ '{"room_id":"room_document_a"}','room_document_a');
+ INSERT INTO memory_index.source_versions(source_id,sha256,manifest,content,size_bytes)
+ VALUES($1,$5,'{"date":"2026-11-16"}',$7,octet_length($7))`, pgx.QueryExecModeSimpleProtocol,
+ "mis_"+hex.EncodeToString(sourceKey[:12]), wikiAdmissionHuman(index),
+ fmt.Sprintf("agent_admission_%d", index), hex.EncodeToString(sourceKey[:]),
+ hex.EncodeToString(contentKey[:]), sessionKey, content); err != nil {
+ t.Fatal(err)
+ }
+ }
+ config := pool.Config()
+ tracer := &serializationFailureTracer{}
+ config.ConnConfig.Tracer = tracer
+ config.MaxConns = int32(humans + 4)
+ traced, err := pgxpool.NewWithConfig(ctx, config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(traced.Close)
+ return document.New(traced), pool, tracer
+}
+
+func wikiAdmissionHuman(index int) string {
+ return fmt.Sprintf("actor_admission_human_%d", index)
+}
+
+// runWikiAdmissionsTogether releases every request at once.
+func runWikiAdmissionsTogether(count int, request func(index int)) {
+ start := make(chan struct{})
+ var group sync.WaitGroup
+ for index := range count {
+ group.Go(func() {
+ <-start
+ request(index)
+ })
+ }
+ close(start)
+ group.Wait()
+}