Custom recall component for the PAI-Rec engine

Updated at:

Implement a custom recall component based on FeatureDBCFRecall, covering environment setup, data preparation, code implementation, testing, and validation.

This recall component filters out triggers with negative weights.

1. Environment preparation

1.1 Project structure

pairec_base/
├── conf/
│   └── config.json              # Main configuration file
├── src/
│   ├── controller/
│   │   └── feed.go              # Feed API controller
│   ├── recall/
│   │   ├── featuredb_cf_recall.go    # Custom recall component
│   │   └── user_item_weight_recall_test.go  # Integration test
│   ├── sql/
│   │   ├── create_table.sql     # MaxCompute table creation statements
│   │   └── generate_test_data.py # Test data generation script
│   │   └── variable.sh        # Environment variable configuration file
│   └── main.go                  # Service entry point
└── vendor/
    └── github.com/alibaba/pairec/v2/  # Framework vendor code

1.2 Dependency installation

# Go 1.21+ environment
go version

# Install dependencies (already vendored, no extra action is usually needed)
go mod tidy

1.3 FeatureStore configuration

Configure the following in the Alibaba Cloud console:

  1. Create a FeatureStore project (e.g., fs_test_project)

  2. Create a FeatureDB instance and set its password (for accessing the FeatureStore API)

  3. Get your Alibaba Cloud access key ID and access key secret (for accessing the FeatureStore API)

1.4 Environment variable configuration

Create the src/sql/variable.sh file and configure the runtime environment variables:

#!/bin/bash

# FeatureStore environment variable configuration
# Usage: source ./variable.sh

export PAIREC_FS_REGION_ID="cn-beijing"
export PAIREC_FS_ACCESS_KEY_ID="<your_access_key_id>"
export PAIREC_FS_ACCESS_KEY_SECRET="<your_access_key_secret>"
export PAIREC_FS_PROJECT_NAME="<your_project_name>"
export PAIREC_PAI_PROJECT_NAME="<your_pai_project_name>"

export PAIREC_FS_FEATUREDB_USERNAME="<your_featuredb_username>"
export PAIREC_FS_FEATUREDB_PASSWORD="<your_featuredb_password>"
export PAIREC_FS_FEATUREDB_ENDPOINT="<your_featuredb_addr>"
export PAIREC_FS_FEATUREDB_TOKEN=""
export PAIREC_FS_INSTANCE_ID=""

echo "========================================"
echo "FeatureStore environment variables loaded."
echo "========================================"

Environment variable descriptions:

Parameter

Description

Example

PAIREC_FS_REGION_ID

The FeatureStore region.

cn-beijing

PAIREC_FS_ACCESS_KEY_ID

Your Alibaba Cloud access key ID.

-

PAIREC_FS_ACCESS_KEY_SECRET

Your Alibaba Cloud access key secret.

-

PAIREC_FS_PROJECT_NAME

The name of your FeatureStore project.

-

PAIREC_PAI_PROJECT_NAME

The name of your PAI project.

-

PAIREC_FS_FEATUREDB_USERNAME

Your FeatureDB username.

-

PAIREC_FS_FEATUREDB_PASSWORD

Your FeatureDB password.

-

PAIREC_FS_FEATUREDB_ENDPOINT

The FeatureDB endpoint address.

paifeaturestore.cn-beijing.aliyuncs.com

Usage:

# Load the environment variables
source src/sql/variable.sh

# Start the service
export PAIREC_FS_TEST_MODE=true
./pairec_server -config ./conf/config.json

2. Data preparation

2.1 MaxCompute table schema design

User behavior sequence table (KKV table)

-- demo_user_behavior_table: Stores real-time user behavior sequences.
CREATE TABLE IF NOT EXISTS demo_user_behavior_table (
    user_id         STRING COMMENT 'User ID (first-level key in KKV)',
    item_id         STRING COMMENT 'Item ID (second-level key in KKV)',
    event           STRING COMMENT 'Event: click/order/dislike/collect',
    play_time       DOUBLE COMMENT 'Event duration in seconds',
    event_unix_time BIGINT COMMENT 'Event timestamp in milliseconds'
)
COMMENT 'User behavior sequence table'
PARTITIONED BY (ds STRING COMMENT 'Date partition yyyyMMdd')
LIFECYCLE 30;

Item collaborative relationship table (KV table)

-- demo_i2i_collaborative: Stores item-to-item collaborative filtering relationships.
CREATE TABLE IF NOT EXISTS demo_i2i_collaborative (
    item_id             STRING COMMENT 'Item ID (key in KV)',
    similar_item_ids    STRING COMMENT 'List of similar items, e.g., "item1:score1,item2:score2"'
)
COMMENT 'Item collaborative relationship table'
PARTITIONED BY (ds STRING COMMENT 'Date partition yyyyMMdd')
LIFECYCLE 30;

2.2 FeatureStore view configuration

Create the following views in the FeatureStore console:

View name

Type

Data source

Description

demo_user_behavior_table

Sequence Feature View

MaxCompute table

User behavior sequence, KKV query mode

demo_i2i_collaborative

Feature View

MaxCompute table

Item collaborative relationship, KV query mode

2.3 Test data generation

Run the Python script to generate test data:

# Generate test data SQL
cd src/sql
python3 generate_test_data.py > test_data.sql

# View the generated SQL
cat test_data.sql

Example output:

INSERT OVERWRITE demo_user_behavior_table PARTITION (ds='20260304')
VALUES 
    ('user_001', 'item_123', 'click', 15.5, 1741017600),
    ('user_001', 'item_201', 'dislike', 0, 1741017700);

INSERT OVERWRITE demo_i2i_collaborative PARTITION (ds='20260304')
VALUES 
    ('item_123', 'item_456:0.95,item_789:0.80'),
    ('item_201', 'item_211:0.95,item_212:0.80');

Create the MaxCompute tables and run the generated SQL statements in a MaxCompute client or DataWorks.


3. Custom recall code implementation

3.1 Core logic of the recall component

Create the file src/recall/featuredb_cf_recall.go:

package recall

import (
	"encoding/json"
	"fmt"
	gosort "sort"
	"strconv"
	"strings"
	"time"

	"github.com/alibaba/pairec/v2/context"
	"github.com/alibaba/pairec/v2/log"
	"github.com/alibaba/pairec/v2/module"
	"github.com/alibaba/pairec/v2/persist/fs"
	"github.com/alibaba/pairec/v2/recconf"
	precall "github.com/alibaba/pairec/v2/service/recall"
	"github.com/alibaba/pairec/v2/utils"
)

var _ precall.Recall = (*FeatureDBCFRecall)(nil)

const FeatureDBCFRecallName = "FeatureDBCFRecall"

// FeatureDBCFRecallConf is a custom configuration struct parsed from UserDefineConfs.
type FeatureDBCFRecallConf struct {
	RecallCount              int
	Name                     string
	RealTimeUser2ItemDaoConf recconf.RealTimeUser2ItemDaoConfig
}

type featureDBCFMyConf struct {
	FeatureDBCFRecallConf FeatureDBCFRecallConf
}

// FeatureDBCFRecall implements a real-time collaborative filtering recall component based on FeatureDB data.
//
// Its core difference from the standard UserItemWeightRecall is that it filters out trigger
// items with weights less than 0 before performing item-to-item (I2I) collaborative filtering.
//
// Recall process:
//  1. Reads user behavior sequences from FeatureStore to calculate the weight of each trigger item.
//  2. Filters out trigger items with a weight less than 0.
//  3. Uses the remaining valid triggers to query the I2I collaborative relationship table for a set of candidate items.
//  4. Sorts the candidates by score in descending order, removes duplicates, and truncates the list to RecallCount.
type FeatureDBCFRecall struct {
	recallName         string
	recallCount        int
	triggerDAO         module.RealTimeUser2ItemDao // Fetches trigger information from FeatureDB.
	fsClient           *fs.FSClient                // Client for querying the I2I collaborative relationship table.
	itemTable          string                      // Name of the I2I collaborative relationship FeatureView.
	similarItemIdField string                      // Field name for similar item IDs.
	config             FeatureDBCFRecallConf
}

// NewFeatureDBCFRecall creates a FeatureDBCFRecall instance and reads the configuration from UserDefineConfs.
func NewFeatureDBCFRecall() *FeatureDBCFRecall {
	config, err := recconf.ParseUserDefineConfs[featureDBCFMyConf]()
	if err != nil {
		panic(fmt.Sprintf("FeatureDBCFRecallConf parse error:%v", err))
	}
	return newFeatureDBCFRecallWithConfig(config.FeatureDBCFRecallConf)
}

func newFeatureDBCFRecallWithConfig(conf FeatureDBCFRecallConf) *FeatureDBCFRecall {
	r := &FeatureDBCFRecall{
		config:             conf,
		recallName:         conf.Name,
		recallCount:        conf.RecallCount,
		itemTable:          conf.RealTimeUser2ItemDaoConf.Item2ItemFeatureViewName,
		similarItemIdField: "similar_item_ids",
	}

	if conf.RealTimeUser2ItemDaoConf.SimilarItemIdField != "" {
		r.similarItemIdField = conf.RealTimeUser2ItemDaoConf.SimilarItemIdField
	}

	// Initialize the trigger DAO using the standard FeatureStore adapter to read user behavior sequences.
	recallConf := recconf.RecallConfig{
		Name:                     conf.Name,
		RecallCount:              conf.RecallCount,
		RealTimeUser2ItemDaoConf: conf.RealTimeUser2ItemDaoConf,
	}
	r.triggerDAO = module.NewRealTimeUser2ItemDao(recallConf)

	// Initialize the FeatureStore client for I2I collaborative relationship queries.
	fsclient, err := fs.GetFeatureStoreClient(conf.RealTimeUser2ItemDaoConf.UserTriggerDaoConf.FeatureStoreName)
	if err != nil {
		panic(fmt.Sprintf("FeatureDBCFRecall: GetFeatureStoreClient error=%v", err))
	}
	r.fsClient = fsclient

	log.Info(fmt.Sprintf("FeatureDBCFRecall: initialized name=%s recallCount=%d itemTable=%s",
		r.recallName, r.recallCount, r.itemTable))

	return r
}

// GetCandidateItems performs real-time collaborative filtering recall with weight-based filtering.
//
// Steps:
//  1. Fetches user trigger items and their weights from FeatureDB.
//  2. Filters out triggers with a weight less than 0 (this is the key difference).
//  3. If no I2I table is configured, returns the valid trigger items as the candidate set.
//  4. Otherwise, queries the I2I collaborative relationship table to get candidate items.
//  5. Sorts, deduplicates, and truncates the result set.
func (r *FeatureDBCFRecall) GetCandidateItems(user *module.User, ctx *context.RecommendContext) []*module.Item {
	start := time.Now()

	if r.triggerDAO == nil {
		log.Error(fmt.Sprintf("requestId=%s\tmodule=FeatureDBCFRecall\terror=triggerDAO not initialized", ctx.RecommendId))
		return []*module.Item{}
	}

	// Step 1: Get trigger information, which includes weight calculation.
	triggerInfos := r.triggerDAO.GetTriggerInfos(user, ctx)

	if len(triggerInfos) == 0 {
		log.Info(fmt.Sprintf("requestId=%s\tmodule=FeatureDBCFRecall\tname=%s\tno triggers found\tcost=%d",
			ctx.RecommendId, r.recallName, utils.CostTime(start)))
		return []*module.Item{}
	}

	// Step 2: Filter out trigger items with weights less than 0 (core business logic).
	validTriggers := r.filterNegativeWeightTriggers(triggerInfos, ctx)
	if len(validTriggers) == 0 {
		log.Info(fmt.Sprintf("requestId=%s\tmodule=FeatureDBCFRecall\tname=%s\tall triggers filtered by weight<0\tcost=%d",
			ctx.RecommendId, r.recallName, utils.CostTime(start)))
		return []*module.Item{}
	}

	// Build a trigger map (triggerId -> weight) and an ordered slice of trigger IDs.
	itemTriggers := make(map[string]float64, len(validTriggers))
	triggerIds := make([]string, 0, len(validTriggers))
	for _, t := range validTriggers {
		itemTriggers[t.ItemId] = t.Weight
		triggerIds = append(triggerIds, t.ItemId)
	}

	log.Info(fmt.Sprintf("requestId=%s\tmodule=FeatureDBCFRecall\tname=%s\toriginalTriggers=%d\tvalidTriggers=%d",
		ctx.RecommendId, r.recallName, len(triggerInfos), len(validTriggers)))

	// Step 3: If no I2I table is configured, use the valid trigger items as the candidate set.
	var ret []*module.Item
	if r.itemTable == "" {
		for _, t := range validTriggers {
			item := module.NewItem(t.ItemId)
			item.RetrieveId = r.recallName
			item.Score = t.Weight
			ret = append(ret, item)
		}
		ret = r.sortAndTruncate(ret)
		log.Info(fmt.Sprintf("requestId=%s\tmodule=FeatureDBCFRecall\tname=%s\tcount=%d\tcost=%d",
			ctx.RecommendId, r.recallName, len(ret), utils.CostTime(start)))
		return ret
	}

	// Step 4: Query the I2I collaborative relationship table to expand the candidate set for each valid trigger.
	ret = r.recallByI2I(itemTriggers, triggerIds, ctx)

	log.Info(fmt.Sprintf("requestId=%s\tmodule=FeatureDBCFRecall\tname=%s\tcount=%d\tcost=%d",
		ctx.RecommendId, r.recallName, len(ret), utils.CostTime(start)))

	return ret
}

// filterNegativeWeightTriggers filters out trigger items with a weight less than 0.
// A weight less than 0 typically indicates a negative signal from the user (e.g., a 'dislike' or 'report').
// These items should not be used as a source for collaborative filtering triggers.
func (r *FeatureDBCFRecall) filterNegativeWeightTriggers(
	triggers []*module.TriggerInfo,
	ctx *context.RecommendContext,
) []*module.TriggerInfo {
	valid := make([]*module.TriggerInfo, 0, len(triggers))
	filtered := 0
	for _, t := range triggers {
		log.Info(fmt.Sprintf("user trigger:%+v", t))
		if t.Weight < 0 {
			filtered++
			fmt.Println(fmt.Sprintf("user filter trigger:%+v", t))
			if ctx.Debug {
				log.Info(fmt.Sprintf(
					"requestId=%s\tmodule=FeatureDBCFRecall\tfiltered trigger\titemId=%s\tweight=%f",
					ctx.RecommendId, t.ItemId, t.Weight))
			}
			continue
		}
		valid = append(valid, t)
	}
	if filtered > 0 {
		log.Info(fmt.Sprintf("requestId=%s\tmodule=FeatureDBCFRecall\tname=%s\tfiltered negative triggers=%d",
			ctx.RecommendId, r.recallName, filtered))
	}

	return valid
}

// recallByI2I expands the candidate set for valid triggers by using the FeatureStore I2I collaborative relationship table.
func (r *FeatureDBCFRecall) recallByI2I(
	itemTriggers map[string]float64,
	triggerIds []string,
	ctx *context.RecommendContext,
) []*module.Item {
	featureView := r.fsClient.GetProject().GetFeatureView(r.itemTable)
	if featureView == nil {
		log.Error(fmt.Sprintf(
			"requestId=%s\tmodule=FeatureDBCFRecall\trecallName=%s\terror=featureView not found: %s",
			ctx.RecommendId, r.recallName, r.itemTable))
		return nil
	}

	featureEntity := r.fsClient.GetProject().GetFeatureEntity(featureView.GetFeatureEntityName())
	if featureEntity == nil {
		log.Error(fmt.Sprintf(
			"requestId=%s\tmodule=FeatureDBCFRecall\trecallName=%s\terror=featureEntity not found: %s",
			ctx.RecommendId, r.recallName, featureView.GetFeatureEntityName()))
		return nil
	}

	// Batch query for I2I similar items.
	itemIds := make([]interface{}, 0, len(triggerIds))
	for _, id := range triggerIds {
		itemIds = append(itemIds, id)
	}

	features, err := featureView.GetOnlineFeatures(itemIds, []string{r.similarItemIdField}, nil)
	if err != nil {
		log.Error(fmt.Sprintf("requestId=%s\tmodule=FeatureDBCFRecall\terror=GetOnlineFeatures(%v)", ctx.RecommendId, err))
		return nil
	}

	var ret []*module.Item
	triggerIdItemMap := make(map[string][]*module.Item, len(itemTriggers))

	for _, featureMap := range features {
		triggerId := utils.ToString(featureMap[featureEntity.FeatureEntityJoinid], "")
		similarIds := utils.ToString(featureMap[r.similarItemIdField], "")
		preferScore := itemTriggers[triggerId]

		list := strings.Split(similarIds, ",")
		for _, entry := range list {
			parts := strings.Split(entry, ":")
			if len(parts) == 0 || parts[0] == "" || parts[0] == "null" {
				continue
			}

			item := module.NewItem(parts[0])
			item.RetrieveId = r.recallName

			switch len(parts) {
			case 2:
				// Format: itemId:score
				if score, err := strconv.ParseFloat(strings.TrimSpace(parts[1]), 64); err == nil {
					item.Score = score * preferScore
				} else {
					item.Score = preferScore
				}
			case 3:
				// Compatible format: itemId:recallName:score
				if score, err := strconv.ParseFloat(strings.TrimSpace(parts[2]), 64); err == nil {
					item.Score = score * preferScore
				} else {
					item.Score = preferScore
				}
			default:
				item.Score = preferScore
			}

			ret = append(ret, item)
			triggerIdItemMap[triggerId] = append(triggerIdItemMap[triggerId], item)
		}
	}

	if ctx.Debug {
		for _, triggerId := range triggerIds {
			if items, ok := triggerIdItemMap[triggerId]; ok && len(items) > 0 {
				log.Info(fmt.Sprintf(
					"requestId=%s\tmodule=FeatureDBCFRecall\ttriggerId=%s\ttriggerScore=%f\titems=%s",
					ctx.RecommendId, triggerId, itemTriggers[triggerId], r.debugItemsString(items)))
			}
		}
	}

	return r.sortAndTruncate(ret)
}

// sortAndTruncate sorts candidate items by score in descending order, removes duplicates, and truncates the list to recallCount.
func (r *FeatureDBCFRecall) sortAndTruncate(items []*module.Item) []*module.Item {
	// Sort by score in descending order.
	gosort.Slice(items, func(i, j int) bool {
		return items[i].Score > items[j].Score
	})

	// Remove duplicates.
	seen := make(map[module.ItemId]bool, len(items))
	deduped := make([]*module.Item, 0, len(items))
	for _, item := range items {
		if !seen[item.Id] {
			seen[item.Id] = true
			deduped = append(deduped, item)
		}
	}

	// Truncate the list.
	if len(deduped) > r.recallCount {
		deduped = deduped[:r.recallCount]
	}
	return deduped
}

func (r *FeatureDBCFRecall) debugItemsString(items []*module.Item) string {
	parts := make([]string, 0, len(items))
	for _, item := range items {
		parts = append(parts, fmt.Sprintf("%s:%f", item.Id, item.Score))
	}
	return strings.Join(parts, ",")
}

// CloneWithConfig clones a new FeatureDBCFRecall instance based on A/B testing parameters.
func (r *FeatureDBCFRecall) CloneWithConfig(params map[string]interface{}) *FeatureDBCFRecall {
	d, err := json.Marshal(params)
	if err != nil {
		log.Error(fmt.Sprintf("module=FeatureDBCFRecall\terr=%v", err))
		return nil
	}
	config := FeatureDBCFRecallConf{}
	err = json.Unmarshal(d, &config)
	if err != nil {
		log.Error(fmt.Sprintf("module=FeatureDBCFRecall\terr=%v", err))
		return nil
	}
	return newFeatureDBCFRecallWithConfig(config)
}

3.2 Service entry point registration

Modify src/main.go:

package main

import (
	"pairec_demo/src/controller"
	"pairec_demo/src/recall"

	"github.com/alibaba/pairec/v2"
	precall "github.com/alibaba/pairec/v2/service/recall"
)

func main() {
	// Pre-register the custom recall component before calling Run().
	pairec.AddStartHook(func() error {
		precall.RegisterRecall(recall.FeatureDBCFRecallName, recall.NewFeatureDBCFRecall())
		return nil
	})

	pairec.Route("/api/rec/feed", &controller.FeedController{})
	pairec.Run()
}

4. Configuration

4.1 Complete config.json

Create the conf/config.json file:

{
	"RunMode": "prepub",
	"ListenConf": {
		"HttpAddr": "",
		"HttpPort": 8000
	},
	"RecallConfs": [],
	"SortNames": {
		"default": ["ItemRankScore"]
	},
	"FilterNames": {
		"default": []
	},
	"SceneConfs": {
		"home_feed": {
		     "default": {
			"RecallNames": ["FeatureDBCFRecall"]
		     }
		}
	},
	"LogConf": {
		"RetentionDays": 3,
		"DiskSize": 20,
		"LogLevel": "DEBUG",
		"Output": "console"
	},
	"FeatureStoreConfs": {
		"fs_pairec": {
			"RegionId": "<your_region_id>",
			"AccessId": "<your_access_key_id>",
			"AccessKey": "<your_access_key_secret>",
			"ProjectName": "<your_project_name>",
			"FeatureDBUsername": "<your_featuredb_username>",
			"FeatureDBPassword": "<your_featuredb_password>",
			"TestMode": true
		}
	},
	"UserDefineConfs": {
		"FeatureDBCFRecallConf": {
			"Name": "FeatureDBCFRecall",
			"RecallCount": 200,
			"RealTimeUser2ItemDaoConf": {
				"UserTriggerDaoConf": {
					"AdapterType": "featurestore",
					"FeatureStoreName": "fs_pairec",
					"FeatureStoreViewName": "demo_user_behavior_table",
					"TriggerCount": 100,
					"EventWeight": "click:1;order:-1;dislike:-2",
					"WeightExpression": "exp((-0.2)*((currentTime-eventTime)/3600/24))",
					"WeightMode": "sum",
					"NoUsePlayTimeField": true,
					"ItemIdFieldName": "item_id",
					"EventFieldName": "event",
					"TimestampFieldName": "event_unix_time"
				},
				"Item2ItemFeatureViewName": "demo_i2i_collaborative",
				"SimilarItemIdField": "similar_item_ids"
			}
		}
	}
}

Parameter descriptions:

Parameter

Description

Placeholder

RegionId

The FeatureStore region.

<your_region_id>

AccessId

Your Alibaba Cloud access key ID.

<your_access_key_id>

AccessKey

Your Alibaba Cloud access key secret.

<your_access_key_secret>

ProjectName

The name of your FeatureStore project.

<your_project_name>

FeatureDBUsername

Your FeatureDB username.

<your_featuredb_username>

FeatureDBPassword

Your FeatureDB password.

<your_featuredb_password>

Important: Replace all <...> placeholders with your actual values. Do not commit real credentials to a code repository.

4.2 Key configuration parameters

Configuration path

Description

Example value

RecallConfs[].Name

The name of the recall component.

featuredb_cf_recall

RecallConfs[].RecallType

The recall type identifier.

FeatureDBCFRecall

UserTriggerDaoConf.FeatureStoreName

The name of the FeatureStore configuration.

fs_pairec

UserTriggerDaoConf.FeatureStoreViewName

The name of the user behavior view.

demo_user_behavior_table

Item2ItemFeatureViewName

The name of the I2I collaborative view.

demo_i2i_collaborative

EventWeight

The event weight mapping.

click:1;order:-1;dislike:-2

WeightExpression

The time decay formula.

exp((-0.2)*((currentTime-eventTime)/3600/24))

FeatureStoreConfs[].TestMode

Enables test mode.

true (Required for local development)

Change to false for production.


5. Testing and validation

5.1 Unit testing

# Run the unit test for the filtering logic.
go test ./src/recall/... -run TestFilterNegativeWeightTriggers -v

5.2 Integration testing

Set environment variables

export PAIREC_FS_REGION_ID=cn-beijing
export PAIREC_FS_ACCESS_KEY_ID=<your_access_key_id>
export PAIREC_FS_ACCESS_KEY_SECRET=<your_access_key_secret>
export PAIREC_FS_PROJECT_NAME=fs_test_project
export PAIREC_FS_FEATUREDB_USERNAME=<your_featuredb_username>
export PAIREC_FS_FEATUREDB_PASSWORD=<your_featuredb_password>

Run the integration test

# Run the complete integration test.
go test ./src/recall/... -run TestFeatureDBCFRecall_Integration -v -timeout 60s

5.3 Service startup test

Compile the service

# Compile the service.
go build -o pairec_server src/main.go

Start the service

# Set environment variables and start the service.
export PAIREC_FS_TEST_MODE=true
./pairec_server -config ./conf/config.json

API test

# Send a test request.
curl -s -X POST "http://localhost:8000/api/rec/feed" \
  -H "Content-Type: application/json" \
  -d '{
    "uid": "user_001",
    "scene_id": "home_feed",
    "size": 10,
    "debug": true
  }' | python3 -m json.tool

Expected response:

{
    "code": 200,
    "msg": "success",
    "request_id": "xxx",
    "size": 10,
    "items": [
        {"id": "item_456", "score": 0.95},
        {"id": "item_789", "score": 0.80}
    ]
}

6. Troubleshooting

6.1 Recall logs are missing

Symptom: No FeatureDBCFRecall logs appear after the service starts.

Cause: service.Load() is called before AddStartHook registers the custom recall component.

Solution: Ensure that you use AddStartHook to register the recall component in main.go.

6.2 FeatureStore 403 authentication error

Symptom: StatusCode: 403, Response message: auth error.

Solution:

  1. Verify that config.json contains the correct AccessId and AccessKey.

  2. Verify that FeatureDBPassword is the latest password.

  3. Confirm that TestMode is set to true.

6.3 "no triggers found" error

Symptom: The logs show a no triggers found message.

Troubleshooting Steps:

  1. Confirm that the MaxCompute tables contain data.

  2. Confirm that the FeatureStore views are synchronized correctly.

  3. Check that the request user_id matches a user ID in the data (e.g., user_001).

  4. Check the timestamp unit (it should be milliseconds).

6.4 VPC address timeout

Symptom: Connections to the FeatureStore VPC address from a public IP address time out.

Solution:

# Set the PAIREC_FS_TEST_MODE environment variable to connect using a public IP address.
export PAIREC_FS_TEST_MODE=true

7. Key design points

7.1 Negative weight filtering logic

// Filter triggers with a weight less than 0 (e.g., 'dislike' or 'order' events).
func (r *FeatureDBCFRecall) filterNegativeWeightTriggers(...) []*module.TriggerInfo {
    valid := make([]*module.TriggerInfo, 0, len(triggers))
    for _, t := range triggers {
        if t.Weight < 0 {
            continue  // Skip negative-weight triggers.
        }
        valid = append(valid, t)
    }
    return valid
}

7.2 Weight calculation formula

weight = eventWeight * timeDecay

# eventWeight: The weight of the event type (e.g., click:1, order:-1, dislike:-2).
# timeDecay:   The time decay factor, e.g., exp((-0.2)*((currentTime-eventTime)/3600/24)).

7.3 Recall process

1. Read the user behavior sequence (from demo_user_behavior_table).
2. Calculate the weight of each trigger item.
3. Filter out triggers with a weight less than 0.
4. Query the I2I collaborative table (demo_i2i_collaborative).
5. Expand the list of similar items and calculate their final scores.
6. Sort, deduplicate, truncate, and return the results.

8. Appendix

8.1 Event weight configuration

Event

Weight

Description

click

1

A positive signal.

collect

2

A strong positive signal.

order

-1

An order or purchase. Exclude to avoid recommending an already-purchased item.

dislike

-2

A strong negative signal.

share

3

The strongest positive signal.

8.2 Time decay formula

Formula

Half-life

Scenarios

exp((-0.2)*((currentTime-eventTime)/3600/24))

~3.5 days

News, short videos

exp((-0.1)*((currentTime-eventTime)/3600/24))

~7 days

E-commerce, products

exp((-0.05)*((currentTime-eventTime)/3600/24))

~14 days

Long-cycle content